Mongoose可选搜索查询参数?

fiv*_*ven 9 mongoose mongodb node.js

我有以下情况.我需要基于某些参数(如果存在)构建一个mongoose查询.

即如果这样的对象被传递

{
    player: "nickname",
    action: "capture"
}
Run Code Online (Sandbox Code Playgroud)

执行以下搜索:

Entry.find({
    player: obj.player,
    action: obj.action
}).
    exec(function(err, res){
        console.log(res);
    });
Run Code Online (Sandbox Code Playgroud)

如果我需要从搜索中排除"操作",如果操作不在对象中,我该怎么办?使用三元运算符一样action: (obj.action) ? obj.action:null不起作用,如将搜索条目DB哪里actionnull.

Joh*_*yHK 21

以编程方式构建查询对象:

var query = {
    player: 'player'
};

if (obj.action) {
    query.action = obj.action;
}

Entry.find(query).exec(function(err, res){
    console.log(res);
});
Run Code Online (Sandbox Code Playgroud)


Mr5*_*5o1 9

使用 ES6,您可以使用 splat 和三元来完成此操作,如下所示:

Entry.find({
  player: obj.player,
  ...obj.action ? { action: obj.action } : {}
})
.exec(function(err, res){
    console.log(res);
});
Run Code Online (Sandbox Code Playgroud)


fiv*_*ven 5

如果有人遇到同样的问题,我是这样解决的:

var query = {
    player: 'player'
};

Entry.find({
    player: query.player,
    action: (query.action) ? query.action:/.*/
}).
    exec(function(err, res){
        console.log(res);
    });
Run Code Online (Sandbox Code Playgroud)

  • 这种方法的一个缺点是使用正则表达式会损害查询性能。最好从查询中省略该字段。 (5认同)