mongoose库
Schema
Schema定义了一种聚合的规则
var userSchema = new Schema({
name:{
type:String,
unique:true,
required:true
},
age:{
type:Number,
min:1,
max:100
},
brothDay:{
type:String,
match:/[1-31]day$/i
},
brothMonth:{
type:String.
enum:['1月','2月','...','11月','12月']
}
})
通过schema可以初步的校验数据规则,当校验规则不正确的时候,会返回一个错误对象,格式如下:
{
message: 'Validation failed',
name: 'ValidationError',
errors:{
email:{
message: 'Validator "required" failed for path email',
name: 'ValidatorError',
path: 'email',
type: 'required'
},
name:{
message: 'Validator "required" failed for path name',
name: 'ValidatorError',
path: 'name',
type: 'required'
}
}
}
自定义schema验证规则
var lengthVal = function(val) {
if (val && val.length >= 5){
return true;
}
return false;
};
//usage: 当不满足验证规则时返回的msg为错误描述
name: {type: String, required: true, validate: {validator:lengthVal,msg:'error desc'}}
//添加多个验证规则
var validators = [{validator:validator1,msg:'error desc1'},{validator:validator2,msg:'error desc2'}]
name: {type: String, required: true, validate:validators}
//离散的添加若干个验证规则
userSchema.path('name').validate(lengthVal, 'Too short');
userSchema.path('name').validate(/^[a-z]+$/i, 'Letters only');