mongoose 是一个对象文档模型(ODM)库
可以为文档创建一个模式结构(Schema)
可以对模型中的对象/文档进行验证
数据可以通过类型转换转换为模型
对象
可以使用中间件应用业务逻辑
使用 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 数据库的连接状态