码迷,mamicode.com
首页 > 其他好文 > 详细

Mongoose指南 - 验证

时间:2015-03-12 15:01:43      阅读:170      评论:0      收藏:0      [点我收藏+]

标签:

开始前记住下面几点

  • 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

  

Mongoose指南 - 验证

标签:

原文地址:http://www.cnblogs.com/irocker/p/4332263.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!