mongoose 是一个对象文档模型(ODM)库

https://mongoosejs.com/

5.1 mongoose 提供的新对象类型

5.2 简单使用 ongoose

https://mongoosejs.com/docs/guide.html

使用 mongoose 返回的是一个 mogoose Query object, mongoose 执行 query 语句后的结果会被传进 callback 函数 callback(error, result)

A mongoose query can be executed in one of two ways. First, if you pass in a callback function, Mongoose will execute the query asynchronously and pass the results to the callback.

A query also has a .then() function, and thus can be used as a promise.

const q = MyModel.updateMany({}, { isDeleted: true }, function() {
  console.log("Update 1");
}));

q.then(() => console.log("Update 2"));
q.then(() => console.log("Update 3"));

上面这一段代码会执行三次 updateMany() 操作, 第一次是因为 callback, 之后的两次是因为 .then() (因为 .then() 也会调用 updatemany())

连接数据库并且创建 Model 类

const mongoose = require('mongoose');
// test is the name of database, will be created automatically
mongoose.connect('mongodb://localhost:27017/test', {useNewUrlParser: true});

const Cat = mongoose.model('Cat', { name: String });

const kitty = new Cat({ name: 'Zildjian' });
kitty.save().then(() => console.log('meow'));

监听 MongoDB 数据库的连接状态