在进行数据保存时,你可以通过 validation 配置项,以防止将数据完整性破坏。
如果你要使用验证,注意几个点:
pre('save')
钩子注册在 schema 上doc.validate(callback)
或 doc.validateSync()
手动验证required
验证器Model#save
,子文档验证也会执行,出错的话 Model#save
回调会接收错误required
:表示必填字段const schema = new Schema({name: {type: String,// 第二个参数是错误提示信息required: [true, 'name is required'],},});
min
和 max
:用于 Number 类型的数据设置限制const schema = new Schema({eggs: {type: Number,min: [6, 'Too few eggs'],max: 12,},});
enum
:枚举,表示属性值只能为这些match
:匹配正则表达式maxlength
:字符串最大长度minlength
:字符串最小长度const schema = new Schema({drink: {type: String,enum: ['Coffe', 'Tea'],},food: {type: String,match: /^a/,maxlength: 12,minlength: 6,},});
const schema = new Schema({phone: {type: String,validate: {validator: function (data) {return /\d{3}-\d{3}-\d{4}/.test(data);},// VALUE 代表 phone 存放的值message: '{VALUE} is not a valid phone number',},required: [true, 'User phone number required'],},});
const Cat = db.model('Cat', schema);// This cat has no nameconst cat = new Cat();cat.save(function (error) {assert.equal(error.errors['name'].message, 'Path `name` is required');error = cat.validateSync();});