简体   繁体   中英

Node JS Mongoose update query inside for or foreach loop, is it possible?

I have 2 different objects inside an array, and i want to use those objects to update a collection in my mongodb So i though about using something like this:

for (i = 0 ; i < array.length ; i++) {
Model.update({array[i]._id},{$set : {'credits_pending' : array[i].credits_pending}},false,true)
}

But it only updates the first value of my array, i mean, array[0]

Why?

For one thing, update (and most other operations) in Mongoose is asynchronous so you need to wait till the operation is done before continuing. It's usually better to do one operation at a time on the same collection. With the for loop, you're running two asynchronous operations at the same time on the same collection, which might give an undesired behavior.

Second, I think your Model.update() arguments are slightly off.

I like to use async.js when working with Mongoose, so below is an example on how you can update an array of objects one at a time.

var async = require('async');

async.eachSeries(array, function updateObject (obj, done) {
    // Model.update(condition, doc, callback)
    Model.update({ _id: obj._id }, { $set : { credits_pending: obj.credits_pending }}, done);
}, function allDone (err) {
    // this will be called when all the updates are done or an error occurred during the iteration
});

I don't know how your schema looks like but if that is the only way to do that, try something like -

//array - your original array
        async.eachSeries(array, function(rec, callback) {
             updateRecord(rec._id, rec.credits_pending)
                  .then((updated) => {
                      callback();
                    })
        }, function(err){
          //execution comes here when array is fully iterated.
        });

    function updateRecord(id, credits) {
    return Model.update({array[i]._id},{$set : {'credits_pending' : array[i].credits_pending}});
    }  

Mongoose internally supports promise so you don't have to worry about anything else.
"Note" - For updating multiple documents you should select some property that is common to all the documents. This approach is not correct and you should design your schema to avoid such scenarios. This answer is in the case you don't have any other choice.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM