Mongoose 数据校验
内置数据校验方法
- required 表示这个数据必须传入
- max 用于 Number 类型数据 最大值
- min 用于 Number 类型数据 最小值
- enum 枚举类型 要求数据必须满足枚举值
- match 增加的数据必须符合 match(正则) 的规则
- maxlength 最大值
- minlength 最小值
const UserSchema = mongoose.Schema({ name: { type: String, required: true, // name 字段必须传递 validate: function (name) { // 自定义验证器 return name.length >= 2 && name.length <= 5 } }, sn: { type: String, index: true, // 添加索引 minlength: 10, // 长度最小10位 maxlength: 20, // 长度最大20位 match: /^sn/i, // 该字段必须满足该正则 }, age: { type: Number, min: 0, // 最小值 0 max: 150, // 最大值 150 }, status: { type: String, default: 'success', enum: ['success', 'error'] }, })