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

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


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.