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
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With