开始前记住下面几点
- Validation定义在SchemaType中
- Validation是一个内部的中间件
- 当document要save前会发生验证
- 验证不会发生在空值上 除非对应的字段加上了 required validator
- 可以自定义验证器
内置的验证器
- 所有的SchemaType都有required验证器
- Number有min和max验证器
- String有enum和match验证器
自定义验证器
//确保值是something function validator(val){ return val == "something"; } new Schema({name:{type:String, validate: validator}}); //自定义错误信息 var custom =[validator, ‘{PATH} does not equal something‘]; new Schema({name:{type:String, validate: custome}}); //一次添加多个验证器 var many = [ {validator:validator, msg:‘uh oh‘}, {validator: anotherValidator, msg: ‘failed‘} ]; new Schema({name: {type:String, validate:many}); //or var schema = new Schema({name: ‘string‘}); schema.path(‘name‘).validate(validator, "{PATH} {VALUE}");
var toySchema = new Schema({ color: String, name: String }); var Toy = mongoose.model(‘Toy‘, toySchema); Toy.schema.path(‘color‘).validate(function (value) { return /blue|green|white|red|orange|periwinkle/i.test(value); }, ‘Invalid color‘); var toy = new Toy({ color: ‘grease‘}); toy.save(function (err) { // err is our ValidationError object // err.errors.color is a ValidatorError object console.log(err.errors.color.message) // prints ‘Validator "Invalid color" failed for path color with value `grease`‘ console.log(String(err.errors.color)) // prints ‘Validator "Invalid color" failed for path color with value `grease`‘ console.log(err.errors.color.type) // prints "Invalid color" console.log(err.errors.color.path) // prints "color" console.log(err.errors.color.value) // prints "grease" console.log(err.name) // prints "ValidationError" console.log(err.message) // prints "Validation failed" });
当验证发生错误的时候, document通用会有一个erros属性:
toy.errors.color.message == err.errors.color.message
时间: 2024-10-04 01:41:23