1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
| const db = new mongoose.Schema({ title: { type: String, required: [true, '请传入文章标题'], minlength: [2, '文章长度最小为2'], maxlength: [5, '文章长度最大为5'], trim: true }, age: { type: Number, min: [18, '年龄最小为18'], max: [23, '年龄最大为23'] }, time: { type: Date, default: Date.now }, category: { type: String, enum: { values: ['love', 'like', 'thank'], message: '' } }, author: { type: String, validate: { validator: v => { return v && v.length > 4 }, message: '传入的值不符合验证规则' } } }) const post = mongoose.model('Post', db) post.create({ title: 'dyy222', age: 16, category: 'love22', author: 'you' }) .then(res => console.log(res)) .catch(error => { const err = error.errors; for (let attr in err) { console.log(err[attr]['message']); } })
|