Search code examples
node.jsexpressmongoosegetmongodb-query

Partial string matching - GET request API - Mongoose, Express, Node


I have a GET request which successfully returns restaurants when I type in a restaurant. It uses collation and an index so can find upper or lower case, no problem.

The issue is that I must type in the exact restaurant name, otherwise the GET request fails in Postman.

E.g. To find a restaurant named Riverside Shard Inn, my GET request will only find it if I enter Riverside Shard Inn in the query. If I enter Riverside Shard or Shard Inn this would fail.

So I guess I need partial string matching in the backend. No idea how to do this.

Here's my GET request code:

    // Route to return a single restaurant using a collection that has collation//
    app.route("/restaurants/:restaurantName")
    
    .get(function(req, res){
      Restaurant.find({BusinessName: req.params.restaurantName}, function(err, foundRestaurant){
        if (foundRestaurant) {
          res.send(foundRestaurant)
        } else {
          res.send("No restaurants matching that title was found.");
        }
      });
    });

Solution

  • You can use Regex to search for partial match. The RegExp object is used for matching text with a pattern. So, you can consider your partial-string to be the pattern that needs to be matched in the string.

    So, you could do it like this -

    .get(function(req, res){
      let partialToMatch= new RegExp(req.params.restaurantName,'i'); 
      Restaurant.find({BusinessName: partialToMatch}, function(err, foundRestaurant){
        if (foundRestaurant) {
          res.send(foundRestaurant)
        } else {
          res.send("No restaurants matching that title was found.");
        }
      });
    });
    

    The above code will return a match if any substring of BusinessName matches req.params.restaurantName. Here the i modifier is used to perform case-insensitive matching.

    You can also refer to $regex which can be used to achieve the same. I am not familiar with it and personally have used RegExp when I was working with nodejs with mongoose.

    Hope this helps !