BigBoy1337
BigBoy1337

Reputation: 5003

Mongoose: How can I update a document using a variable in the callback?

I am looping through a list of ids, finding the entry associated with that id, and I want to update a "score" value based on its current value. like so:

id_array= ['2l3k4jixc','2343xjl','l243xkj33',.......];
var K=5;
for (var i=0, i<id_array.length;i++){
Model.findByIdAndUpdate(id_array[i], { $set: { value:update_variable }}, options, function(err,found_item){
    update_variable= ((K-found_item.score)^3)/2;
}
})

right now it is trying to use $set: {score:update_variable} before update_variable has been defined by the callback function. So I think it does not work. How can I do this?

Upvotes: 0

Views: 75

Answers (1)

Neil Lunn
Neil Lunn

Reputation: 151162

Presently there is no way to refer to another field value within any form of update statement in MongoDB in general, so you are generally stuck with "finding" the item and then issuing a separate .save() method:

Model.findById(id_array[i],function(err,found) {
    found.value = ((doc.score)^3)/2;
    found.save();
});

Additional callback in the save is optional ( advised ) to your purpose, but this is the only current way to set one field based on the value of another. So bulk updates are right out unless you are looping.

Upvotes: 1

Related Questions