node.js - How to Validate Mongoose Schema With a Complex Object in Array -


i building schema has complex object in array:

foo:{    bar:[{        itema:string,        itemb:string    }] } 

i want add validation object in array check array size (i want limit size of array 10).

how structure schema validate sort of object in array?

you can through validate option in schema below

var fooschema = new schema({     foo:{        bar: {             type: [{                itema:string,                itemb:string             }],             validate: [arrlimit, '{path} exceeds limit 10']         }     } });  function arrlimit(arr) {     return arr && arr.length <= 10; }; 

if add more 10 items bar array like

var f = foo({}); (var = 0; < 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 come up

{ [validationerror: foo validation failed]   message: 'foo validation failed',   name: 'validationerror',   errors:    { 'foo.bar':       { [validatorerror: foo.bar exceeds limit 10]         properties: [object],         message: 'foo.bar exceeds limit 10',         name: 'validatorerror',         kind: 'user defined',         path: 'foo.bar',         value: [object] } } } 

Comments

Popular posts from this blog

java - Run spring boot application error: Cannot instantiate interface org.springframework.context.ApplicationListener -

reactjs - React router and this.props.children - how to pass state to this.props.children -

Excel VBA "Microsoft Windows Common Controls 6.0 (SP6)" Location Changes -