选项 1(带有“字典”):
您可以使用 Object 构造函数作为 SchemaType 来使用对象而不是对象数组。这是一个使用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
}
}
这不会应用重复键检查,因为对象不能有重复键,后面出现的键只会覆盖前一个键:
> let foo = { bar: 4, bar: 5}
< Object { bar: 5 }
如您所见,前面分配的bar: 4 键被后面的键覆盖。
选项 2(带数组):
您可以使用SchemaType#validate 在某个文档路径上实现您的自定义验证。这是您想要的示例:
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
}
}]
如果您对此进行测试,它将删除数组中具有重复键的对象(保留较早的键)并检查数组是否仅包含具有唯一 category 键的对象。