我正从游戏客户端收到两个或两个变量中的一个: 金额和金额2
我有代码在mongo数据库中执行任务,无论是对于这两个变量还是对于其中一个变量:
if(amount && amount2) mMissionUser.update_task({id_user: id_user, id_mission: id_mission, "tasks.id_task": id_task}, { $set: { "tasks.$.counter": amount, "tasks.$.counter2": amount2 } }, process);
else if(amount && !amount2) mMissionUser.update_task({id_user: id_user, id_mission: id_mission, "tasks.id_task": id_task}, { $set: { "tasks.$.counter": amount } }, process);
else if(!amount && amount2) mMissionUser.update_task({id_user: id_user, id_mission: id_mission, "tasks.id_task": id_task}, { $set: { "tasks.$.counter2": amount2 } }, process);
您是否知道如何在单行MONGODB查询中对其进行简化?
答案 0 :(得分:1)
以编程方式构建$set
对象,然后使用常见update
调用应用它:
var set = {};
if (amount) set["tasks.$.counter"] = amount;
if (amount2) set["tasks.$.counter2"] = amount2;
mMissionUser.update_task(
{id_user: id_user, id_mission: id_mission, "tasks.id_task": id_task},
{$set: set},
process);