[英]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. 我正在遍历一个ID列表,查找与该ID关联的条目,并且我想根据其当前值更新一个“得分”值。 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. 现在,它正在尝试使用
$set: {score:update_variable}
在回调函数定义了$set: {score:update_variable}
之前。 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: 目前,在MongoDB中,通常无法在任何形式的
update
语句中引用另一个字段值,因此通常会陷入“查找”项目,然后发出单独的.save()
方法的.save()
:
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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.