const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/playground', { useNewUrlParser: 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,
max: 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(error => {
const err = error.errors;
for (var attr in err) {
console.log(err[attr]['message']);
}
})