简体   繁体   English

猫鼬:如何在回调中使用变量来更新文档?

[英]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.

相关问题 如何更新Mongoose中的文档? - How can I update a document in Mongoose? 如何在不引用文档本身的情况下使用 mongoose 有条件地更新一个数据库文档? - How can i conditionally update one DB document using mongoose without referencing the document itself? 猫鼬:如何更新/保存文档? - Mongoose: how do I update/save a document? 如何在 Mongoose 中更新/插入文档? - How do I update/upsert a document in Mongoose? 如何使用猫鼬在节点中更新内部文档 - How to update inner document in node using mongoose 如何使用 mongoose findByIdAndUpdate 更新嵌套数据 - How can i update nested data by using mongoose findByIdAndUpdate 如何更新 mongoose 中 createdAt 字段的 expires 属性以避免文档被删除? - How can I update the expires property on createdAt field in mongoose to avoid the document being deleted? 如何复制整个 JavaScript object 以更新包含嵌套 arrays 和子文档的 MongoDB/Mongoose 文档? - How can I copy an entire JavaScript object to update a MongoDB/Mongoose document, that contains nested arrays and subdocuments? 如何使用 mongoose 在单个 mongodb 文档中更新数组中的多个对象 - How to update multiple objects in array in a single mongodb document using mongoose 如何在 node.js 上使用 mongoose 从 mongodb 库检索文档? - How can I retrieve document from mongodb base using mongoose on node.js?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM