本文介绍了使用 Mongoose 进行动态查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用 Mongoose 创建一个动态条件,但它不像我想象的那样工作.
I am trying to make a dynamic condition using Mongoose but it doesn't work as I imagined.
代码是这样的
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);
如您所见,我正在尝试使用索引"变量创建动态条件.可以这样做吗?
As you see, I am trying to make dynamic condition using "index" variable. Is it possible to do like this?
先谢谢你!
推荐答案
您需要分两步创建 updates
对象:
You need to create your updates
object in two steps:
var updates = { $push: {} };
updates.$push["array.$.array2." + index + ".answeredBy"] = userId;
更新
现在 node.js 4+ 支持 计算属性名称,您可以一步完成:
Now that node.js 4+ supports computed property names, you can do this in one step:
var updates = { $push: {
["array.$.array2." + index + ".answeredBy"]: userId
} };
这篇关于使用 Mongoose 进行动态查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!