Search code examples
javascriptnode.jstypescriptmongoose

NodeJS - TypeScript - URL Query doesn't work if multiple parameters


I have the following controller in my route:

export const getHotels = async (
  req: Request,
  res: Response,
  next: NextFunction
) => {
  try {
    const hotels = await Hotel.find(req.query).limit(+req.query.limit);
    res.status(200).json(hotels);
  } catch (err) {
    next(err);
  }
};

In my database, I have hotels with a featured property (boolean) that I retrieve with Mongoose and reduce the results with its limit method.

I noticed that my query returns an empty array if I have several parameters no matter what if I call (GET): /api/hotels?featured=true&limit=1

It works fine if the controller is await Hotel.find().limit(+req.query.limit); and the URL /api/hotels?limit=1

Or if controller is await Hotel.find(req.query); and URL /api/hotels?featured=true

Does anyone have an idea of what could be the issue? Many thanks.


Solution

  • I realised I wasn't using the object bracket with find() before which is why mongoDB could only take the 1st argument.

    Example:

    const { limit, ...others } = req.query;
        const hotels = await Hotel.find({
          ...others,
        }).limit(+limit);
    

    By doing so, I can add any parameter in my GET request and don't need to use Lodash to pick a specific parameter.