猫鼬-如何告诉猫鼬跳过空参数(如果有)

时间:2020-05-18 06:25:58

标签: node.js mongodb express mongoose

查询

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_utcity将保持为空,而我希望猫鼬跳过这些为空的参数。这是执行此操作的正确方法。我不想通过检查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.searchKeyUndefined时,出现此错误...。

TypeError: Cannot set property 'address.state_ut' of undefined

1 个答案:

答案 0 :(得分:1)

一旦传递给猫鼬,您将无法跳过查询,您应该使用node.js代码本身更新查询。

是的,您不应该创建多个查询,而是应该创建一个查询对象,并根据if / else条件对其进行更新,如下面的示例所述

localhost:8080/my-image.png
相关问题