![](https://img-blog.csdnimg.cn/20210410084456187.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80NTE0Nzg5NA==,size_16,color_FFFFFF,t_70)
// 引入mongoose第三方模块 用来操作数据库
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为字符串,required必传字段为true.
//意思是必须要有title字段
title:{
type:String,
//必选字段
required:[true,'请输入文章标题'],
//字段最小长度
minlength:[2,'文章长度不能少于2'],
//字段最大长度
maxlength:[5,'文章长度不能多于5'],
//去除字符串两边空格
trim:true
},
age:{
type:Number,
min:18,
max:50
}
});
const Post=mongoose.model('Post', postSchema);
Post.create({title:'aaaa',age:10}).then(result=>console.log(result));
![](https://img-blog.csdnimg.cn/20210410084535387.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80NTE0Nzg5NA==,size_16,color_FFFFFF,t_70)
// 引入mongoose第三方模块 用来操作数据库
const mongoose = require('mongoose');
// 数据库连接
mongoose.connect('mongodb://localhost/playground', { useNewUrlParser: true