var schema =newSchema({ name: { type: String, required:true } });var Cat =db.model('Cat', schema);// This cat has no name :(var cat =newCat();cat.save(function(error) {assert.equal(error.errors['name'].message,'Path `name` is required.'); error =cat.validateSync();assert.equal(error.errors['name'].message,'Path `name` is required.'); });
var userSchema =newSchema({ phone: { type: String, validate: {validator:function(v) {return /\d{3}-\d{3}-\d{4}/.test(v); }, message:'{VALUE} is not a valid phone number!' }, required: [true,'User phone number required'] } });var User =db.model('user', userSchema);var user =newUser();var error;user.phone ='555.0123'; error =user.validateSync();assert.equal(error.errors['phone'].message,'555.0123 is not a valid phone number!');user.phone =''; error =user.validateSync();assert.equal(error.errors['phone'].message,'User phone number required');user.phone ='201-555-0123';// Validation succeeds! Phone number is defined// and fits `DDD-DDD-DDDD` error =user.validateSync();assert.equal(error,null);
var userSchema =newSchema({ phone: { type: String, validate: {validator:function(v, cb) {setTimeout(function() {cb(/\d{3}-\d{3}-\d{4}/.test(v)); },5); }, message:'{VALUE} is not a valid phone number!' }, required: [true,'User phone number required'] } });var User =db.model('User', userSchema);var user =newUser();var error;user.phone ='555.0123';user.validate(function(error) {assert.ok(error);assert.equal(error.errors['phone'].message,'555.0123 is not a valid phone number!'); });
验证错误
验证失败后Errors返回一个错误的对象实际上是validatorerror对象。每个ValidatorError有kind, path, value, and message属性。
var toySchema =newSchema({ color: String, name: String });var Toy =db.model('Toy', toySchema);varvalidator=function (value) {return /blue|green|white|red|orange|periwinkle/i.test(value); };Toy.schema.path('color').validate(validator,'Color `{VALUE}` not valid','Invalid color');var toy =newToy({ color:'grease'});toy.save(function (err) {// err is our ValidationError object// err.errors.color is a ValidatorError objectassert.equal(err.errors.color.message,'Color `grease` not valid');assert.equal(err.errors.color.kind,'Invalid color');assert.equal(err.errors.color.path,'color');assert.equal(err.errors.color.value,'grease');assert.equal(err.name,'ValidationError'); });
Required验证在嵌套的对象
定义嵌套对象验证器在mongoose是是棘手的,因为嵌套对象不完全成熟的路径。
var personSchema =newSchema({ name: { first: String, last: String } });assert.throws(function() {// This throws an error, because 'name' isn't a full fledged pathpersonSchema.path('name').required(true); }, /Cannot.*'required'/);// To make a nested object required, use a single nested schemavar nameSchema =newSchema({ first: String, last: String }); personSchema =newSchema({ name: { type: nameSchema, required:true } });var Person =db.model('Person', personSchema);var person =newPerson();var error =person.validateSync();assert.ok(error.errors['name']);
var toySchema =newSchema({ color: String, name: String });toySchema.path('color').validate(function(value) {// When running in `validate()` or `validateSync()`, the// validator can access the document using `this`.// Does **not** work with update validators.if (this.name.toLowerCase().indexOf('red') !==-1) {return value !=='red'; }returntrue; });var Toy =db.model('ActionFigure', toySchema);var toy =newToy({ color:'red', name:'Red Power Ranger' });var error =toy.validateSync();assert.ok(error.errors['color']);var update = { color:'red', name:'Red Power Ranger' };var opts = { runValidators:true };Toy.update({}, update, opts,function(error) {// The update validator throws an error:// "TypeError: Cannot read property 'toLowerCase' of undefined",// because `this` is **not** the document being updated when using// update validatorsassert.ok(error); });
context 选项
context选项允许你在更新验证器设置此值为相关查询。
toySchema.path('color').validate(function(value) {// When running update validators with the `context` option set to// 'query', `this` refers to the query object.if (this.getUpdate().$set.name.toLowerCase().indexOf('red') !==-1) {return value ==='red'; }returntrue; });var Toy =db.model('Figure', toySchema);var update = { color:'blue', name:'Red Power Ranger' };// Note the context optionvar opts = { runValidators:true, context:'query' };Toy.update({}, update, opts,function(error) {assert.ok(error.errors['color']); });
var testSchema =newSchema({ number: { type: Number, max:0 }, });var Test =db.model('Test', testSchema);var update = { $inc: { number:1 } };var opts = { runValidators:true };Test.update({}, update, opts,function(error) {// There will never be a validation error here });