Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 846
Hugo Modesto Avatar asked Apr 05 '17 10:04

Hugo Modesto


1 Answers

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
});
like image 182
Mikey Avatar answered Nov 12 '22 00:11

Mikey