gpt4 book ai didi

javascript - Mongoose 批量更新操作

转载 作者:IT老高 更新时间:2023-10-28 13:32:34 26 4
gpt4 key购买 nike

有没有办法在 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com