簡體   English   中英

用貓鼬進行動態查詢

[英]Make dynamic query with Mongoose

我正在嘗試使用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);

如您所見,我正在嘗試使用“索引”變量創建動態條件。 有可能這樣做嗎?

先感謝您!

您需要分兩步創建updates對象:

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

更新資料

現在,node.js 4+支持計算的屬性名稱 ,您可以一步完成此操作:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM