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

I have two different objects inside an array and I want to use these objects to update the collection in my mongodb So although I am 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?

+3


source to share


2 answers


First, updates (and most other operations) in Mongoose are asynchronous, so you need to wait for the operation to complete before continuing. It is usually best to do one operation at a time on one collection. With a loop, for

you are simultaneously performing two asynchronous operations on the same collection, which can lead to unwanted 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 of 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
});

      

+5


source


I don't know what your circuit looks like, but if this is the only way to do it, 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 maintains promise internally, so you don't have to worry about anything else.
"Note" - to update several documents, you must select some property that is common to all documents. This approach is wrong and you must design a circuit to avoid such scenarios. This answer is in case you have no other choice.

0


source







All Articles