1

Source Code

let placeForSearch="hampi"
let filteredHotelFacilities=req.body.filter //["Free Wifi"]

let hotels = await Hotel.find({placeForSearch})
      .where("facilities")
      .all(filteredHotelFacilities)
      .in(filteredHotelFacilities)
      .select(selectedProperties)
      .skip(pageNumber * pageSize)  
      .limit(pageSize);

The above code finds if any elements of req.body.filter is in the facilities array in the database and the above code outputs the collection given below.

  {
    facilities: [ 'Garden', 'Free Wifi' ],
    _id: 60f066e61e6971412cf5e727,
    placeForSearch: 'hampi'
  },
  {
    facilities: [ 'Free Wifi' ],
    _id: 60f180141121791e2884d6f0,
    placeForSearch: 'hampi'
  }

Database

  {
    facilities: [ 'Garden', 'Free Wifi' ],
    _id: 60f066e61e6971412cf5e727,
    placeForSearch: 'hampi'
  },
  {
    facilities: [ 'Garden', 'AC' ],
    _id: 60f066e61e6971412cf5e727,
    placeForSearch: 'hampi'
  },
  {
    facilities: [ 'Free Wifi' ],
    _id: 60f180141121791e2884d6f0,
    placeForSearch: 'hampi'
  }

Facilities array in the database can have any of the below-given elements or all of them.

  [
    "Free Wifi",
    "Garden",
    "Water park",
    "Spa and wellness centre",
    "Terrace",
    "Fitness centre",
    "Restaurant",
    "Room service",
    "Bar",
    "Hot tub/jacuzzi",
    "Swimming pool",
    "AC"
  ];

So how can I get all collections in the database if the user does not apply any filter?(req.body.filter=[])

In other words how can i remove .all(filteredHotelFacilities).in(filteredHotelFacilities) based on condition.

1 Answer 1

1

You should return a promise(by removing await) and chain query based on condition and at last query use await keyword.

let hotels = Hotel.find({placeForSearch})  //remove await keyword

if (filteredHotelFacilities.length > 0) {
   hotels=hotels.where("facilities")       //remove await keyword
                .all(filteredHotelFacilities)
                .in(filteredHotelFacilities);
     }

hotels = await hotels                     // apply await keyword here
   .select(selectedProperties)
   .skip(pageNumber * pageSize)
   .limit(pageSize);
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.