I am using Mongoose and have a requirement to update many documents based on some calculations.
我正在使用Mongoose,并且需要基于一些计算更新许多文档。
This is easy if I am querying one by one, but if I have say 50 items, I don't want to query and update one by one
如果我一个一个地查询,这很容易,但是如果我有50个条目,我不想一个一个地查询和更新
What I am doing is curating a query to pull back multiple documents so I can loop through them all and make changes.
我正在做的是管理一个查询以收回多个文档,这样我就可以对它们进行循环并进行更改。
However, you can't call save on multiple objects, like you can with findOne. Its my first time with Mongoose, but in Entity Framework, I can edit the returned results from a query and call saveChanges() to update every item that has changed
但是,不能像使用findOne那样调用多个对象的save。这是我第一次使用Mongoose,但是在实体框架中,我可以编辑查询返回的结果,并调用saveChanges()来更新已经更改的每个条目
I want to do something like this
我想做这样的事情
item.find(query).exec(function(err, items) {
for (i in items) {
// change stuff
}
items.save(function (err) {
// saved
}
}
2 个解决方案
#1
2
If u r using Promise library u can do like this:
如果你使用承诺库,你可以这样做:
var Promise = require('bluebird');
var saveQuery=[];
item.find(query).exec(function(err, items) {
for (i in items) {
// change stuff
}
saveQuery.push(item.save()); // Write your save query
}
return Promise.all(saveQuery); // this will do your all save queries at once simultaneously.
#2
0
If you're trying to do some simple changes to these docs, maybe
如果你想对这些文档做一些简单的修改,也许。
update({_id:{$in:[a,b,c]}}, {$inc:{score:1}}, {multi:true}).exec()
could help.
更新({ _id:{ $:[a,b,c]} },{ $ . n:行情):{分数:1 } },{多:真}).exec()可以帮助。
#1
2
If u r using Promise library u can do like this:
如果你使用承诺库,你可以这样做:
var Promise = require('bluebird');
var saveQuery=[];
item.find(query).exec(function(err, items) {
for (i in items) {
// change stuff
}
saveQuery.push(item.save()); // Write your save query
}
return Promise.all(saveQuery); // this will do your all save queries at once simultaneously.
#2
0
If you're trying to do some simple changes to these docs, maybe
如果你想对这些文档做一些简单的修改,也许。
update({_id:{$in:[a,b,c]}}, {$inc:{score:1}}, {multi:true}).exec()
could help.
更新({ _id:{ $:[a,b,c]} },{ $ . n:行情):{分数:1 } },{多:真}).exec()可以帮助。