10. Mongoose 数据校验

在定义Schema的时候设置校验规则,例如:

  1. const UserSchema = new mongoose.Schema({
  2. name:{
  3. type:String,
  4. required: true,
  5. }
  6. })

1. 预定义的校验规则

字段 说明
required 表示这个数据必须传入
max 用于 Number 类型数据,最大值
min 用于 Number 类型数据,最小值
enum 枚举类型,要求数据必须满足枚举值 enum: [‘0’, ‘1’, ‘2’]
match 增加的数据必须符合 match(正则)的规则
maxlength 最大长度
minlength 最小长度

2. 自定义验证器

向validate字段传入一个函数,需要return一个布尔值,true则通过校验,false则不通过

  1. const UserSchema = new mongoose.Schema({
  2. name:{
  3. type:String,
  4. required: true,
  5. validate: name => {
  6. return name.length > 2
  7. }
  8. }
  9. })