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

询问

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"
   }
)

I am taking these filters (location_type, city, state_ut) from user. User may only want to filter result with location_type then state_ut and city will remains null and I want mongoose to skip these parameters which are null. Which is the proper way to do this. I don't want to write many queries by checking with if statements.

评论
alber1986
alber1986

一旦传递给猫鼬,您就不能跳过查询,您应该在node.js代码本身中更新查询。

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

var location_query = {"$text":{
    "$search":"req.body.searchKey"
  }};

// you can add any other condition you want
if (req.body.location_type != undefined) { 
  location_query.location_type = req.body.location_type;
}

if (req.body.state_ut!= undefined) { 
  location_query.state_ut= req.body.state_ut;
} 

if (req.body.city!= undefined) { 
  location_query.city= req.body.city;
} 

Location.find(location_query)
点赞
评论