【问题标题】:Make dynamic query with Mongoose使用 Mongoose 进行动态查询
【发布时间】:2014-06-28 05:28:06
【问题描述】:

我正在尝试使用 Mongoose 制作动态条件,但它并没有像我想象的那样工作。

代码是这样的

id = req.params.questionId;
index = req.params.index;

callback = function(err,value){
   if(err){

       res.send(err)

   }else{

       res.send(value)

    }
};

conditions = {
    "_id": id,
    "array._id": filterId
};
updates = {
   $push: {
      "array.$.array2."+index+".answeredBy": userId
   }
};
options = {
  upsert: true
};

Model.update(conditions, updates, options, callback);

如您所见,我正在尝试使用“索引”变量创建动态条件。这样可以吗?

提前谢谢你!

【问题讨论】:

    标签: javascript node.js mongodb mongoose database


    【解决方案1】:

    您需要分两步创建updates 对象:

    var updates = { $push: {} };
    updates.$push["array.$.array2." + index + ".answeredBy"] = userId;
    

    更新

    现在 node.js 4+ 支持computed property names,你可以一步完成:

    var updates = { $push: {
        ["array.$.array2." + index + ".answeredBy"]: userId
    } };
    

    【讨论】:

    • 或使用 Object.create
    • 你救了我的命。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2017-04-15
    • 1970-01-01
    • 1970-01-01
    • 2017-01-19
    • 2014-08-04
    • 2021-04-25
    • 2021-10-09
    • 2015-04-19
    相关资源
    最近更新 更多