Location.find(
{
"$text":{
"$search":"req.body.searchKey"
},
"location_type":"req.body.location_type",
"address.state_ut":"req.body.state_ut",
"address.city":"req.body.city"
}
)
我正在从用户那里获取这些过滤器(location_type, city, state_ut
)。用户可能只想用location_type
过滤结果,然后state_ut
和city
将保持为空,而我希望猫鼬跳过这些为空的参数。这是执行此操作的正确方法。我不想通过检查if语句来编写许多查询。
var location_query;
if(req.body.searchKey) {
location_query = {"$text":{
"$search": req.body.searchKey
}};
}
if (req.body.location_type) {
location_query["location_type"]= req.body.location_type;
}
if (req.body.state_ut) {
location_query["address.state_ut"]= req.body.state_ut;
}
if (req.body.city) {
location_query["address.city"]= req.body.city;
}
// return res.json({location_query: location_query});
Location.find(location_query)
.then(result => {
console.log(result);
res.status(200).json({ success: true, result: result })
}).catch(err => {
res.json({ success: false, message: err})
})
{
"state_ut":"Daman and Diu"
}
当req.body.searchKey
为Undefined
时,出现此错误...。
TypeError: Cannot set property 'address.state_ut' of undefined
答案 0 :(得分:1)
一旦传递给猫鼬,您将无法跳过查询,您应该使用node.js代码本身更新查询。
是的,您不应该创建多个查询,而是应该创建一个查询对象,并根据if / else条件对其进行更新,如下面的示例所述
localhost:8080/my-image.png