10. Mongoose 数据校验
在定义Schema的时候设置校验规则,例如:
const UserSchema = new mongoose.Schema({name:{type:String,required: true,}})
1. 预定义的校验规则
| 字段 | 说明 |
|---|---|
| required | 表示这个数据必须传入 |
| max | 用于 Number 类型数据,最大值 |
| min | 用于 Number 类型数据,最小值 |
| enum | 枚举类型,要求数据必须满足枚举值 enum: [‘0’, ‘1’, ‘2’] |
| match | 增加的数据必须符合 match(正则)的规则 |
| maxlength | 最大长度 |
| minlength | 最小长度 |
2. 自定义验证器
向validate字段传入一个函数,需要return一个布尔值,true则通过校验,false则不通过
const UserSchema = new mongoose.Schema({name:{type:String,required: true,validate: name => {return name.length > 2}}})
