使用Mongoose进行动态查询

Make dynamic query with Mongoose

本文关键字:动态 查询 Mongoose 使用      更新时间:2023-09-26

我正在尝试使用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);

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

提前感谢!

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

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

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

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