在创建集合规则时,可以设置当前字段的验证规则,验证失败则输出错误提示信息。
const postSchema = new mongoose.Schema({ title: { type: String, required: true, minlength: 2, maxlength: 6, trim: true, min: 10, max: 100 }, publishDate: { type: Date, default: Date.now, validate: v => { // 返回布尔值 // true 验证成功 // false 验证失败 // v 要验证的值 return v && v.length > 4 }, message: ‘你输入的内容不符合‘ } })
验证规则可以一个参数,也可以是多个参数的数组
例如:
// 设定集合规则 const PostSchema = new mongoose.Schema({ title: { type: String, minlength: [4, ‘最小长度为4‘], maxlength: [30, ‘最大长度为30‘], trim: true, required: [true, ‘此项为必填内容‘] }
其中 数组中的第一个参数为验证规则,第二个参数为错误提示信息。
原文:https://www.cnblogs.com/liea/p/11223675.html