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?

有帮助吗?

解决方案

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top