简体   繁体   English

如何使用数组中的复杂对象验证猫鼬模式

[英]How to Validate Mongoose Schema With a Complex Object in Array

I am building a schema which has a complex object in an array: 我正在建立一个在数组中具有复杂对象的架构:

foo:{
   bar:[{
       ItemA:String,
       ItemB:String
   }]
}

I want to add validation to the object in the array so as to check the array size (I want to limit the size of the array to 10). 我想向数组中的对象添加验证,以便检查数组大小(我想将数组大小限制为10)。

How would I structure the schema so as to validate that sort of object in the array? 我将如何构造模式以验证数组中的此类对象?

You can do it through validate option in Schema as below 您可以通过Schema中的validate选项来完成此操作,如下所示

var FooSchema = new Schema({
    foo:{
       bar: {
            type: [{
               ItemA:String,
               ItemB:String
            }],
            validate: [arrlimit, '{PATH} exceeds the limit 10']
        }
    }
});

function arrlimit(arr) {
    return arr && arr.length <= 10;
};

If you add more than 10 items into bar array like 如果您将超过10项目添加到bar数组中,例如

var f = Foo({});
for (var i = 0; i < 12; ++i)
    f.foo.bar.push({ItemA: 'A', ItemB: 'B'});

f.save(function(err) {
    if (err)
        console.log(err);
    else
        console.log('save foo successfully....');
})

Error will come up 错误会出现

{ [ValidationError: Foo validation failed]
  message: 'Foo validation failed',
  name: 'ValidationError',
  errors:
   { 'foo.bar':
      { [ValidatorError: foo.bar exceeds the limit 10]
        properties: [Object],
        message: 'foo.bar exceeds the limit 10',
        name: 'ValidatorError',
        kind: 'user defined',
        path: 'foo.bar',
        value: [Object] } } }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM