猫鼬可选的搜索查询参数?
问题描述:
我有以下情况. 我需要根据某些参数构建猫鼬查询.
I have a following situation. I need to build a mongoose query, based on certain arguments if present.
即如果这样的对象通过了
I.e. if object like this is passed
{
player: "nickname",
action: "capture"
}
执行以下搜索:
Entry.find({
player: obj.player,
action: obj.action
}).
exec(function(err, res){
console.log(res);
});
如果如果动作不在对象中,则需要从搜索中排除动作",该怎么办?
像action: (obj.action) ? obj.action:null
这样使用三元运算符不起作用,就像在action
为null
的DB中搜索条目一样.
If I need to exclude "action" from search if action is not in the object, what should I do?
Using ternary operator like action: (obj.action) ? obj.action:null
doesn't work, as would search entries in DB where action
is null
.
答
以编程方式构建查询对象:
Build up your query object programmatically:
var query = {
player: 'player'
};
if (obj.action) {
query.action = obj.action;
}
Entry.find(query).exec(function(err, res){
console.log(res);
});