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: ['html', 'css', 'javascript']
},
author: {
type: String,
validate: {
validator: v => {
//true 验证成功
//false验证失败v.length>4
return v && v.length > 4
},
//自定义错误信息
message: '传入得值不符合规则'
}
}
});
const Post = mongoose.model('Post', postSchema);
//插入数据
Post.create({ title: 'aa', age: 60, category: 'html', author: '12345' }).then(result => console.log(result));
运行结果