mongoose学习笔记(五)效验参数

tech2025-10-08  4

required : 表示这个数据必须传入

max: 用于 Number 类型数据,最大值

min: 用于 Number 类型数据,最小值

enum:枚举类型,要求数据必须满足枚举值 enum: [‘0’, ‘1’, ‘2’],只适用于字符串

match:增加的数据必须符合match(正则)的规则

maxlength:最大长度

minlength:最小长度

mongoose效验

var UserSchema = new mongoose.Schema({ name:{ type:String, required: true, //name字段必须传入 }, age: { type: Number, // 是否必须的校验器 required: true, // 数字类型的最大值校验器 max: 120, // 数字类型的最小值校验器 min: 0 }, status: { type: String, // 设置字符串的可选值,只适用于字符串 enum: ['0', '1', '2'] }, phone:{ type:Number, match: /^\d{11}$/ //数字开头,数字结尾,长度10位 }, desc: { type: String, maxlength:20, //最大长度位20 minlength:10 //最小长度10 } });

自定义效验

validate: function(desc) { return desc.length >= 10; }

方法同set和get类似,可以自己去定义效验的规则,主要看函数的返回结果,若为true,则效验通过,若为false,则效验不通过。

最新回复(0)