sql >> Base de Datos >  >> NoSQL >> MongoDB

¿Cómo validar claves y valores de objeto en Mongoose Schema?

Opción 1 (con "diccionarios"): Puedes usar el Object constructor como SchemaType para usar un objeto en lugar de una matriz de objetos. Aquí hay un ejemplo que se aplica a su situación usando SchemaType#validate :

offersInCategory: {
  type: Object,
  validate: object => { //our custom validator, object is the provided object
    let allowedKeys = ['Furniture', 'Household', 'Electronicts', 'Other'];
    let correctKeys = Object.keys(object).every(key => allowedKeys.includes(key)); //make sure all keys are inside `allowedKeys`

    let min = 5;
    let max = 10;
    let correctValues = Object.values(object).every(value => value > min && value < max); //make sure all values are in correct range

    return correctKeys && correctValues; //return true if keys and values pass validation
  }
}

Esto no aplica comprobaciones de claves duplicadas porque un objeto no puede tener claves duplicadas , la última clave presente simplemente anula la clave anterior:

> let foo = { bar: 4, bar: 5}
< Object { bar: 5 }

Como puede ver, la barra bar: 4 la clave que se asignó antes se anula con la clave posterior.

Opción 2 (con matriz): Puede usar SchemaType#validate para implementar su validación personalizada en una determinada ruta de documento. Aquí tienes un ejemplo de lo que quieres:

offersInCategory: [{
  validate: {
    validator: array => { //our custom validator, array is the provided array to be validated
      let filtered = array.filter((obj, index, self) => self.findIndex(el => el.category === obj.category) === index); //this removes any duplicates based on object key
      return array.length === filtered.length; //returns true if the lengths are the same; if the lengths aren't the same that means there was a duplicate key and validation fails
    },
    message: 'Detected duplicate keys in {VALUE}!'
  }
  category: {
    type: String, 
    enum: ['Furniture', 'Household', 'Electronicts', 'Other'] //category must be in this enum
  },
  val: {
    type: Number, 
    min: 0, //minimum allowed number is 0
    max: 10 //maximum allowed number is 10
  }
}]

Y si prueba esto, se deshará de los objetos en la matriz con claves duplicadas (manteniendo la anterior) y verificará si la matriz contiene solo objetos con una category única llaves.