我正在尝试使用 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+支持computed property names ,您可以一步完成此操作:
var updates = { $push: {
["array.$.array2." + index + ".answeredBy"]: userId
} };
关于javascript - 使用 Mongoose 进行动态查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23582133/