Mongoose 可选的搜索查询参数? [英] Mongoose optional search query parameters?
本文介绍了Mongoose 可选的搜索查询参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下情况.我需要根据某些参数(如果存在)构建 mongoose 查询.
I have a following situation. I need to build a mongoose query, based on certain arguments if present.
即如果传递这样的对象
{
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
的条目一样.
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);
});
这篇关于Mongoose 可选的搜索查询参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文