Tom*_*kas 2 search filtering mongodb node.js
我正在尝试对多个字段进行基本过滤(搜索),并想询问如何实现它:
Location.find({
$and: [
{ name: { $regex: query.name } },
{ city: query.city },
{ type: query.type }
]
});
Run Code Online (Sandbox Code Playgroud)
我有一个开始,但当然,这将过滤所有领域,$or是不够的.
我的数据如下:
{
"name": "Shop1",
"type": "shop",
"city": "City1"
},
{
"name": "Shop2",
"type": "shop",
"city": "City1"
},
{
"name": "Cafe1",
"type": "cafe",
"city": "City2"
}
Run Code Online (Sandbox Code Playgroud)
目标是能够搜索输入名称,类型和城市.(任何字段都可以为空)
例如:
Shop1 / Shop / City1 => Shop1 Shop / *blank* / City1 => Shop1, Shop2*blank* / Shop / City1 => Shop1, Shop2等等..
先感谢您!
您需要通过检查存在或不存在的参数来创建查询对象
var queryCond = {}
if(query.name){
queryCond.name={$regex:query.name,$options:"i"};
}
if(query.city){
queryCond.city=query.city;
}
if(query.type){
queryCond.type=query.type;
}
Location.find(queryCond);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3410 次 |
| 最近记录: |