const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/playground', { useUnifiedTopology: true }).then(() => console.log('数据库连接成功')).catch(err => console.log(err, '数据库连接失败'))//创建集合规则
const postSchema = new mongoose.Schema({title: {type: String,require: [true, '请传入文章标题'],minlength: [2, '输入长度不能小于2'],maxlength: [5, '输入长度不能大于5'],const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/playground', { useUnifiedTopology: true }).then(() => console.log('数据库连接成功')).catch(err => console.log(err, '数据库连接失败'))//创建集合规则
const postSchema = new mongoose.Schema({title: {type: String,require: [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'],message: '传入得不符合规则'},},author: {type: String,validate: {validator: v => {//true 验证成功//false验证失败v.length>4return v && v.length > 4},//自定义错误信息message: '传入得值不符合规则'}}
});
const Post = mongoose.model('Post', postSchema);
//插入数据
Post.create({ title: 'aa', age: 60, category: 'java', author: '125' }).then(result => console.log(result)).catch(error => {//获取错误信息对象const err = error.errors;//循环错误对象for (var attr in err) {console.log(err[attr]['message'])}});//不允许有空格trim: true},age: {type: Number,//数字得最小范围min: 18,//数字得最大范围max: 100},publishDate: {type: Date,default: Date.now},category: {type: String,enum: ['html', 'css', 'javascript']},author: {type: String,validate: {validator: v => {//true 验证成功//false验证失败v.length>4return v && v.length > 4},//自定义错误信息message: '传入得值不符合规则'}}
});
const Post = mongoose.model('Post', postSchema);
//插入数据
Post.create({ title: 'aa', age: 60, category: 'java', author: '125' }).then(result => console.log(result)).catch(err => {//获取错误信息对象const err = err.errors;//循环错误对象for (var attr in arr) {console.log(err[attr]['message'])}});
运行结果