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?
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?
Share Improve this question asked Apr 5, 2017 at 10:55 Hugo ModestoHugo Modesto 631 silver badge8 bronze badges 2- This approach is not right. If you want update multiple documents, shouldn't you be selecting some property that is mon to all the documents. And if that is not possible, you should use promise. – Mayank Baiswar Commented Apr 5, 2017 at 12:01
- My objective is to update different documents with different values, how do i do that? I didn't find a solution anywhere :/ – Hugo Modesto Commented Apr 5, 2017 at 12:07
2 Answers
Reset to default 16For 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 es 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 mon 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.