You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesi贸n a prueba de IA

Antes: $249

Currency
$209
Suscr铆bete

Termina en:

0 D铆as
1 Hrs
9 Min
1 Seg

Validando arrays y subdocumentos

9/22
Resources

How to validate complex data in database documents?

In the world of software development, maintaining data integrity is a fundamental task. Validating data is not only limited to primitive types such as strings or numbers, we must also handle more complex structures, such as arrays and subdocuments. I will show you how to perform these validations using JSON Schema to maintain the integrity of the information in your collections.

How to manage arrays in documents?

To validate arrays within documents, we have to make sure to specify both the type of the array and the type of its elements. For example, if you manage an inventory of products and you want to record the available sizes of T-shirts (L, M, XL), you can set the following rules:

  • Array type: Define that the data arrives in the form of an array.
  • Type of elements in the array: Ensure that each element in the array is a string.
  • Unique validity: Each size must be unique within the array.
  • Minimum number of elements: There must be at least one size present in the array.

The code to validate an array of sizes would look like the following:

{ " bsoneType": "array", " items": { " bsoneType": "string" }, " uniqueItems": true, " minItems": 1}

How to ensure integrity in subdocuments?

Subdocuments allow encapsulating related data within a single main document. For example, if a product has a category with its own name and image, we can define this structure clearly:

  1. Type of the subdocument: Defend that the category is an object.
  2. Subdocument properties: Explicitly declare the type of each property, in this case, name and image being strings.
  3. Required fields: Specify that certain information is mandatory.

This is how you should define a subdocument in a JSON Schema:

{ " type": "object", " properties": { " category": { " bsoneType": "object", " properties": { " name": {"bsoneType": "string"}, " image": {"bsoneType": "string"} }, " required": ["name"] } }} } }

Why is it important to maintain validations?

Maintaining these validation rules is crucial to protect the integrity of the data you handle within noSQL databases. A well-defined validation scheme allows you to have effective controls over:

  • The structure of the data entered.
  • The consistency and accuracy of the data.
  • The prevention of unnecessary duplicates.

These practices also improve the efficiency of your system's operation by ensuring that the data handled complies with certain standards before it is stored. In addition, they invite you to continue learning and exploring data validation through other advanced techniques, such as the use of regular expressions.

Now that you have a solid foundation, I encourage you to put your knowledge to the test and explore new forms of validation that go beyond the above. The next challenge is to try regular expressions to validate passwords, and I'll be here to guide you through the next steps!

Contributions 5

Questions 2

Sort by:

Want to see more contributions, questions and answers from the community?

La validacion de docuemtnos que se insertan se puede hacer por

  • Campos requeridos
  • Tipo de dato
  • Para los tipos numericos
    • Minimo
    • Maximo
  • Arrays
    • Permitr o no repetidos
    • Minimo de elementos
  • Tipo de dato
  • Expresiones regulares
    • Correo
    • Password
    • IPs
  • Documentos internos
    • Se aplican todas las validaciones nuevamente
use("platzi_store");

db.products.drop();
db.createCollection("products", {
  validator: {
    $jsonSchema: {
      bsonType: "object",
      required: ["name"],
      properties: {
        name: {
          bsonType: "string",
        },
        sizes: {
          bsonType: "array",
          minItems: 1,
          uniqueItems: true,
          items: {
            bsonType: "string",
          },
        },
        category: {
          bsonType: "object",
          required: ["name"],
          properties: {
            name: {
              bsonType: "string",
            },
            image: {
              bsonType: "string",
            },
          },
        },
      },
    },
  },
});
db.products.find()

Arrays

Conjunto de elementos en una lista. Se puede:

  • Ajustar el esquema de los items
  • Puede bloquearse la repeticion de elementos
  • Asignar una cantidad minima y maxima de elemetos

En crear colecci贸n:

sizes: {
    bsonType: 'array', // es de tipo array
    uniqueItems: true, // no se puede repetir elementos
    minItems: 1, // cantidad minima de elementos
    maxItems: 3, // cantidad maxima de elementos
    items: { // esquema de los items del array
        bsonType: 'string' // los elementos son de tipo string
    }
}

Insertar elemento:

db.products.insertOne({
    name: 'camiseta',
    sizes: ['S', 'L']
})

SubDocumento

Es un documento (objeto) dentro de otro. Si se asigna como tipo de bson object a una propiedad, pasa a ser un sub-documento.

Crear colecci贸n con un sub-documento de categoria:

db.createCollection('products', {
    validator: {
        $jsonSchema: {
            bsonType: 'object',
            required: [...],
            properties: {
                name: {...},
                size: {...},
                category: { // propiedad que es un subdocumento
                    bsonType: 'object', // tipo objeto
                    required: ['name', 'image'], // requerimientos propios
                    properties: { // las propiedades del sub-documento
                        name: {
                            bsonType: 'string'
                        },
                        image: {
                            bsonType: 'string'
                        }
                    }
                }
            }
        }
    }
})

Insertar elemento:

db.products.insertOne({
    name: 'camiseta',
    category: {
        name: 'ropa deportiva',
        image: 'img/camiseta.png'
    }
})
Ahora hacer una lista de objetos que tienen un subdocumento :D, me encontr茅 una asi en mi trabajo