2014-05-10 92 views
0

我想用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); 

正如你看到的,我想用“指数”变化,使动态条件。有没有可能这样做?

预先感谢您!

回答

4

您需要在两个步骤创建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 
} }; 
+0

或与Object.create –

+0

你救了我的命。谢谢! – masanorinyo