代码:
const mongoose = require('mongoose')
mongoose.connect('mongodb://localhost/test1', { useNewUrlParser: true })
.then(() => console.log('数据库连接成功'))
.catch(err => console.log('数据连接失败' + err))
// 设定集合规则
const PostSchema = new mongoose.Schema({
title: {
type: String,
minlength: [4, '最小长度为4'],
maxlength: [30, '最大长度为30'],
trim: true,
required: [true, '此项为必填内容']
},
article: {
type: String,
minlength: [5, '最小长度为5'],
required: [true, '此项为必填内容']
}
})
// 创建集合并应用规则
const Post = mongoose.model('Post', PostSchema)
Post.create({ title: '测试测试测试', article: '内容内容内容'})
.then( res => console.log(res))
.catch( err => {
// console.log(err.errors)
// 循环错误信息对象
for (var attr in err.errors) {
// 打印错误信息
console.log('错误信息:' + err.errors[attr].message)
}
})