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

Time:01-06

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.

CodePudding user response:

When your GET request is /api/hotels?featured=true&limit=1, the req.query content is:

{
  featured: "true",
  limit: "1"
}

...therefore the Hotel.find(req.query) looks for documents with both "featured" field as "true" AND "limit" field as "1"... hence it does not find anything.

You could make sure to extract only necessary fields, e.g. with Lodash pick utility:

Hotel
  .find(pick(req.query, ["featured"]))
  .limit( req.query.limit)

CodePudding user response:

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.

  • Related