猫鼬可选的搜索查询参数? [英] Mongoose optional search query parameters?

查看:59
本文介绍了猫鼬可选的搜索查询参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下情况. 我需要根据某些参数构建猫鼬查询.

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这样使用三元运算符不起作用,就像在actionnull的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);
});

这篇关于猫鼬可选的搜索查询参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆