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
Add a ment  | 

2 Answers 2

Reset to default 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.  

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