Express.js adding a query parameter

1k views Asked by At

I'm trying to add a query parameter in Express. This would be an optional parameter. I want to add a number limit, to limit the amount of responses returned.

So I tried this URL:

http://localhost:3000/restaurants/mowgli?limitQuery=4

With this code:

app.route("/restaurants/:restaurantName")

  .get(function(req, res) {
    let partialToMatch = new RegExp(req.params.restaurantName, 'i');
    
    let limitQuery = req.query.limitQuery
    console.log(limitQuery);
    

    Restaurant.find({
      BusinessName: partialToMatch
    }, null, {
      limit: limitQuery
    }, function(err, foundRestaurant) {
      if (foundRestaurant) {
        res.send(foundRestaurant)
      } else {
        res.send("No restaurants matching that title was found.");
      }
    });
  });

But it throws an error 'No restaurants matching that title was found.'. The console successfully logs the limitQuery parameter, but it seems to go wrong when passed to the limit field.

Note: If I don't use an optional query parameter, by removing the limitQuery variable and revert back to my old code (and hard code a number in the limit field e.g. limit: 25) it all works fine.

1

There are 1 answers

0
vern funnell On

Solved - the variable limitQuery was coming back as a string instead of an integer. So I changed with parseInt and now it passes a number to the limit field and works. Here was the extra code I used to fix my problem:

var limmy = parseInt(limitQuery, 10);

Then in the Restaruant.find query the limit field looks like this:

limit: limmy