mongoDB的验证规则
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/playground', { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => {
console.log('数据库连接成功');
})
.catch((err) => {
console.log(err, '数据库连接失败');
});
const postSchema = new mongoose.Schema({
title: {
type: String,
required: [true, '请传入文章标题'],
minlength: [2, '文章长度不能小于2'],
maxlength: [5, '文章长度不能大于5'],
trim: true
},
age: {
type: Number,
min: [18, '最小的年纪是18'],
max: [100, '最大的年纪是100']
},
publishDate: {
type: Date,
default: Date.now
},
category: {
type: String,
enum: {
values: ['html', 'css', 'javascript', 'node.js'],
message: '分类名称要在一定的范围内才可以'
}
},
author: {
type: String,
validate: {
validator: (v) => {
return v && v.length > 4
},
message: '传入的规则不符合验证规则'
}
}
});
const Post = mongoose.model('Post', postSchema);
Post.create({ title: 'aa', age: 60, category: 'java', author: 'bd' }).then(result => {
console.log(result);
}).catch(err => {
const error = err.errors;
for (var attr in error) {
console.log(error[attr]['message']);
}
})