我在 mongodb docs 中看到可以在单个更新命令中发送多个更新语句。您将如何使用 Node.js 和 Mongoose 来做到这一点?
db.runCommand({
update: <collection>,
updates:
[
{ q: <query>, u: <update>, upsert: <boolean>, multi: <boolean> },
{ q: <query>, u: <update>, upsert: <boolean>, multi: <boolean> },
{ q: <query>, u: <update>, upsert: <boolean>, multi: <boolean> },
...
],
ordered: <boolean>,
writeConcern: { <write concern> }
})
看来我们可以像这样访问驱动程序的数据库对象。
YourModel.db.db
有兴趣知道是否有一种对 Mongoose 更友好的方法?
最佳答案
对于 mongoose 来说,目前还没有具体的任何实现。但在编写时,mongoose API 仍然构建在 Node native 驱动程序之上,这使得可以使用 .collection
访问器从模型访问所有相同的方法。
所以 Bulk API然后可以使用方法:
var bulk = Model.collection.initializeOrderedBulkOp();
var index = 0
// start some loop of statements
{
bulk.find({ }) // find to match
.updateOne({}); // update one
bulk.find({})
.update({}); // applies to multi
bulk.find({})
.upsert().updateOne(); // marks an "upsert"
}
bulk.execute(function(err,response) {
// response object has details of operations
});
此外,还有可以包含在“批量”批处理中的所有其他方法,例如 .insert()
和 .remove()
,因此此方法有效比原始命令形式更干净一些。这实际上就是将其分解为底层的内容。
请注意,基本驱动程序方法的工作方式与 mongoose 方法实现的工作方式不同。最大的区别在于与数据库的连接。 Mongoose 连接的方式以及如何在连接回调之外调用语句意味着它自己的方法在尝试执行任何操作之前“等待”建立该连接。
因此您可以使用它,但您需要确保在调用此代码之前始终已触发某些其他“mongoose”方法。或者以其他方式放置在连接回调或您需要的任何连接检测和保证方法中。
关于javascript - Mongoose - 如何使用多个更新语句进行单个更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27966977/