简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM