ECS Roman
ECS Roman

Reputation: 79

Mongoose - How do I tell mongoose to skip null parameters if there is any

Query

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.

Updated

Code

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

Search Query from user

{
  "state_ut":"Daman and Diu"
}

Error

When the req.body.searchKey is Undefined I get this error....

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

Upvotes: 1

Views: 494

Answers (1)

Puneet Singh
Puneet Singh

Reputation: 3543

You can't skip queries once passed to mongoose, you should update the query in node.js code itself.

Yes you should not create multiple queries, instead, you should create a single query object and update it on the basis of if/else conditions, as mentioned in the example below

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

Upvotes: 1

Related Questions