搜索mongoose的多查询

时间:2017-12-17 17:24:13

标签: node.js mongodb

我想编写高级查询以在mongoose中搜索使用nodejs,

search.js(nodejs)的代码

let queryOptions = {};

if(req.body.title){
    queryOptions.title = {$regex:key ,$options:"i"};
}   
if(req.body.name){
    queryOptions.name = {$regex:key ,$options:"i"};
}
if(req.body.tags){
    queryOptions.tags = {$regex:key ,$options:"i"};
}

Room.find({$or: [queryOptions]}, (err,rooms)=>{})

表单数据像这样

key:"hello"
name:false
tags:false
title:true
当检查了两个属性

时,

mongoose返回空结果

key:"hello"
name:true
tags:false
title:true

1 个答案:

答案 0 :(得分:1)

这是因为您的查询错误

使用此

let queryOptions = [];

if(req.body.title){
    queryOptions.push({title: {$regex:key ,$options:"i"}})
}   
// ...

Room.find({$or: queryOptions}, (err,rooms)=>{})