模型是从Schema定义编译的构造函数,模型的实例称为文档。模型负责从底层MongoDB数据库创建和读取文档。
1. 编译第一个模型
var schema = new mongoose.Schema({ name: 'string', size: 'string' }); var Tank = mongoose.model('Tank', schema);
以上我们通过.model()
方法编译了Tank模型。其中,第一个参数是模型所使用用集合的单数名称中,Mongoose会自动推断出模型名称的复数版本。因此,对于上面的示例,模型Tank在数据库中集合名称为tanks。.model()
方法会生成shcema
的副本,在调用.model()
方之前,请确保已添加了要使用的的所有shcema
。
2. 构建文档
模型的实例称为文档(document),创建文档并保存到数据库非常简单:
var Tank = mongoose.model('Tank', yourSchema); var small = new Tank({ size: 'small' }); small.save(function (err) { if (err) return handleError(err); // saved! }); // or Tank.create({ size: 'small' }, function (err, small) { if (err) return handleError(err); // saved! }); // or, for inserting large batches of documents Tank.insertMany([{ size: 'small' }], function(err) { });
需要注意,在模型使用的连接打开之前,不会创建/删除tank。每个模型都有一个与之关联的连接,使用mongoose.model()
时,模型将使用默认的mongoose连接。
mongoose.connect('localhost', 'gettingstarted');
如果要使用自定义连接,请用连接(connection)的model()
方法来替代:
var connection = mongoose.createConnection('mongodb://localhost:27017/test'); var Tank = connection.model('Tank', yourSchema);
在连接多个数据库时,connection.model()
很有用。
3. 查询
使用Mongooose查找文档很容易,它支持MongoDB的富查询语法。Document可以通过models
的find, findById, findOne或where等静态方法获得。
Tank.find({ size: 'small' }).where('createdDate').gt(oneYearAgo).exec(callback);
4. 删除
Model有deleteOne()
和deleteMany()
静态方法,用于删除指定filter
所匹配的文档。
Tank.deleteOne({ size: 'large' }, function (err) { if (err) return handleError(err); // deleted at most one tank document });
5. 更新
每个Model都有自己的更新方法,用于修改数据库中的文档而无需将其返回到应用中。具体可以参阅API。
如果要修改单个文档并将文档返回给应用,可以使用findOneAndUpdate
方法。
6. 更改流
MongoDB 3.6.0+及Mongoose 5.0.0+ 新特性
更改流提供了一种监听MongoDB数据库中所有插入和更新的方法。注意,除非你连接到MongoDB副本集,否则更改流不起作用。
async function run() { // Create a new mongoose model const personSchema = new mongoose.Schema({ name: String }); const Person = mongoose.model('Person', personSchema, 'Person'); // Create a change stream. The 'change' event gets emitted when there's a // change in the database Person.watch(). on('change', data => console.log(new Date(), data)); // Insert a doc, will trigger the change stream handler above console.log(new Date(), 'Inserting doc'); await Person.create({ name: 'Axl Rose' }); }
上面异步函数返回如下:
2018-05-11T15:05:35.467Z 'Inserting doc' 2018-05-11T15:05:35.487Z 'Inserted doc' 2018-05-11T15:05:35.491Z { _id: { _data: ... }, operationType: 'insert', fullDocument: { _id: 5af5b13fe526027666c6bf83, name: 'Axl Rose', __v: 0 }, ns: { db: 'test', coll: 'Person' }, documentKey: { _id: 5af5b13fe526027666c6bf83 } }
更多关于在mongoose中使用更改流的介绍参考博文:Change Streams in Mongoose。
更多
除上述方法外,Model还有count, mapReduce, aggregate等方法,详见API文档。
变更记录
- [2019-03-15] 基于Mongoose官方文档
v5.4.19
首次发布