1 const mongoose = require('mongoose');
2
3 mongoose.connect('mongodb://localhost/playground')
4 .then(() => console.log('数据库链接成功'))
5 .catch(err => console.log(err, '数据库链接失败') );
6
7 // 创建集合规则
8 const courseSchema = new mongoose.Schema({
9 name: String,
10 author: String,
11 isPublished: Boolean
12 });
13
14 // 使用规则创建集合 1.集合名称 2.集合规则
15 const Course = mongoose.model('Course', courseSchema);
16 // 创建文档
17 const course = new Course({
18 name: 'node.js基础',
19 author: '黑马讲师',
20 isPublished: true
21 });
22 // 将文档插入到数据库中
23 course.save();
![](https://img2020.cnblogs.com/blog/718318/202009/718318-20200915143847835-1445642775.png)