Node.js Mongoose-如果有空参数,我如何告诉Mongoose跳过空参数 查询

Node.js Mongoose-如果有空参数,我如何告诉Mongoose跳过空参数 查询,node.js,mongodb,express,mongoose,Node.js,Mongodb,Express,Mongoose,我从用户那里获取这些过滤器(位置、类型、城市、州)。用户可能只想使用location\u type过滤结果,然后state\u ut和city将保持空值,我希望mongoose跳过这些空值参数。这是正确的方法。我不想通过检查if语句来编写很多查询 更新 代码 搜索来自用户的查询 错误 当req.body.searchKey为Undefined时,我得到这个错误 { "state_ut":"Daman and Diu" } 一旦传递到mongoose,

我从用户那里获取这些过滤器(
位置、类型、城市、州)。用户可能只想使用
location\u type
过滤结果,然后
state\u ut
city
将保持空值,我希望mongoose跳过这些空值参数。这是正确的方法。我不想通过检查if语句来编写很多查询

更新 代码 搜索来自用户的查询 错误 当
req.body.searchKey
Undefined
时,我得到这个错误

{
  "state_ut":"Daman and Diu"
}

一旦传递到mongoose,就不能跳过查询,应该在node.js代码中更新查询

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

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

location\u query.address.state\u ut
location\u query.address.city
可以吗?对不起,我错过了地址,更新了答案,现在可以了。我会尝试一下,让你知道:竖起大拇指:你能帮我更新错误代码吗?
{
  "state_ut":"Daman and Diu"
}
TypeError: Cannot set property 'address.state_ut' of undefined
    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})
    })