Mongoose 校验参数
原创
©著作权归作者所有:来自51CTO博客作者苍青浪1的原创作品,请联系作者获取转载授权,否则将追究法律责任
mongoose数据校验是指用户通过mongoose给mongodb数据库增加数据的时候,对数据的合法性进行的验证,在mongoose里面定义Schema的时候,通过设置字段类型,修饰符、默认参数 、数据校验等都是为了数据库数据的一致性。
required
: 表示这个数据必须传入
max
: 用于 Number 类型数据,最大值
min
: 用于 Number 类型数据,最小值
enum
:枚举类型,用于String要求数据必须满足枚举值 enum: ['0', '1', '2']
match
:增加的数据必须符合 match(正则)的规则
maxlength
:最大值
minlength
:最小值
var mongoose=require('./db.js');
var UserSchema=mongoose.Schema({
name:{
type:String,//指定类型
trim:true, //修饰符
required:true //该数据不能缺省
},
sn:{
type:String,
index:true, //普通索引.
set(val){ //自定义修饰符
return val;
},
// maxlength:20,//长度不能超过20
// minlength:10//长度不能小于10
// match:/^sn(.*)/ ,//必须符合该正则表达式
validate: function(sn) {//自定义验证规则
return sn.length >= 10;
}
// 也可以是
validator: function(v) {
return /\d{3}-\d{3}-\d{4}/.test(v);
},
message: props => `${props.value} is not a valid phone number!`
},
},
age:{
type:Number,
min:0, //用在number类型上面
max:150//最大值为150
},
status:{
type:String,
default:'success', //默认值
enum:['success','error'] //status的值必须在 对应的数组里面 注意枚举是用在String
}
})
module.exports=mongoose.model('User',UserSchema,'user');
const breakfastSchema = new Schema({
eggs: {
type: Number,
min: [6, 'Must be at least 6, got {VALUE}'], // 可以传一个数组 {VALUE}会被替换为校验的值
max: 12
},
drink: {
type: String,
enum: {
values: ['Coffee', 'Tea'],
message: '{VALUE} is not supported'
}
}
});
const Breakfast = db.model('Breakfast', breakfastSchema);
const badBreakfast = new Breakfast({
eggs: 2,
drink: 'Milk'
});
let error = badBreakfast.validateSync();
assert.equal(error.errors['eggs'].message,
'Must be at least 6, got 2');
assert.equal(error.errors['drink'].message, 'Milk is not supported');
const breakfastSchema = new Schema({
eggs: {
type: Number,
min: [6, 'Too few eggs'],
max: 12
},
bacon: {
type: Number,
required: [true, 'Why no bacon?']
},
drink: {
type: String,
enum: ['Coffee', 'Tea'],
required: function() { // 也可以是自定义的函数
return this.bacon > 3;
}
}
});
const Breakfast = db.model('Breakfast', breakfastSchema);
const badBreakfast = new Breakfast({
eggs: 2,
bacon: 0,
drink: 'Milk'
});
let error = badBreakfast.validateSync();
assert.equal(error.errors['eggs'].message,
'Too few eggs');
assert.ok(!error.errors['bacon']);
assert.equal(error.errors['drink'].message,
'`Milk` is not a valid enum value for path `drink`.');
badBreakfast.bacon = 5;
badBreakfast.drink = null;
error = badBreakfast.validateSync();
assert.equal(error.errors['drink'].message, 'Path `drink` is required.');
badBreakfast.bacon = null;
error = badBreakfast.validateSync();
assert.equal(error.errors['bacon'].message, 'Why no bacon?');