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哪里action是null.
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)
使用 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)
如果有人遇到同样的问题,我是这样解决的:
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)
| 归档时间: |
|
| 查看次数: |
7349 次 |
| 最近记录: |