使用Mongoose进行动态查询

mas*_*nyo 0 javascript database mongoose mongodb node.js

我试图使用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);
Run Code Online (Sandbox Code Playgroud)

如您所见,我正在尝试使用"index"变量创建动态条件.有可能这样做吗?

先感谢您!

Joh*_*yHK 6

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

var updates = { $push: {} };
updates.$push["array.$.array2." + index + ".answeredBy"] = userId;
Run Code Online (Sandbox Code Playgroud)

更新

现在node.js 4+支持计算属性名称,您可以一步完成:

var updates = { $push: {
    ["array.$.array2." + index + ".answeredBy"]: userId
} };
Run Code Online (Sandbox Code Playgroud)