admin管理员组文章数量:1429645
I am using Mongoose and have a requirement to update many documents based on some calculations.
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
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
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
}
}
I am using Mongoose and have a requirement to update many documents based on some calculations.
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
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
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
}
}
Share
Improve this question
asked Dec 13, 2016 at 11:49
MichaelMcCabeMichaelMcCabe
5234 gold badges15 silver badges33 bronze badges
2 Answers
Reset to default 2If 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.
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.
本文标签: javascriptMongoose find many and update allStack Overflow
版权声明:本文标题:javascript - Mongoose find many and update all - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745516329a2661561.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论