javascript - Mongoose 批量更新操作

标签 javascript node.js mongodb mongoose

有没有办法在 mongoose 中对集合进行批量更新?我发现的策略使用原始收集驱动程序如下:

var bulk = Person.collection.initializeOrderedBulkOp();
bulk.find(query).update(update);
...
bulk.execute(callback)

但是,当我这样做时,bulk 是未定义的。 mongoose不支持吗?

最佳答案

NOTE: Modern Mongoose releases support .bulkWrite() directly on the Model methods. It is preferable to use this method even in direct implementations of the MongoDB API, since it actually "safely downgrades" to use "individual calls" for the methods supplied in the batch in cases where connecting to a MongoDB version that does not support the "Bulk API" itself.

It still calls the same underlying "bulk methods" as described, but rather the software makes the decision how to correctly send to the server than your own code needing to make this determination.

Also note: That Ongoing mongoose releases now require you to .connect() in a way that means the connection must be resolved before other actions continue. Using new connection mechanisms ensures that accessors such as .collection described below are always present when you call them.


您可以这样做,但问题是当从基本驱动程序访问底层集合对象时,没有采取与实现的 Mongoose 模型方法相同的预防措施。

所有模型方法都使用其他功能包装底层方法,但最常见的是在尝试访问该方法之前确保数据库连接已打开。这确保了 Db 实例存在并且可以获取 Collection() 对象

一旦您在模型上使用了 .collection 访问器,那么您就可以自己完成这一切:

mongoose.connection.on('open',function(err,conn) {

   // now it's safe to use

   // { .. } Other code
   var bulk = Person.collection.initializeOrderedBulkOp();
   bulk.find(query).update(update);
   bulk.execute(callback)

});

或其他一些基本上可以确保实际建立连接的方法。

至于在不深入底层驱动程序级别的情况下对 Bulk API 方法的 native 支持,是的,目前正在研究中。但是您仍然可以自己实现它,只要您连接到 MongoDB 2.6 服务器实例或更高版本,它就不会破坏代码。

关于javascript - Mongoose 批量更新操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27783575/

相关文章:

javascript - 使用 JavaScript 解析日志

javascript - jQuery/PHP - 将数据从 JS 传递到 PHP 以对数据库执行删除

用于计算参数值的 MapReduce

node.js - GraphQL 错误 : Must provide name

ruby-on-rails - 当有自定义 _id 时,mongo-ruby-driver 不会在 upsert 上创建新文档

javascript - 使用javascript替换图像和文本

javascript - 如何从 classname onclick 获取位置?

html - 使用 $routeProvider 是否节省网络带宽?

node.js - 使用 Node JS 库的 Azure 服务总线队列的最大吞吐量?

node.js - Node 中的 Mocking 依赖(主要用于单元测试)