Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (50.2k points)

In my MongoDB app, I have set up a search feature. The below code works very well but it only returns exact results. I want to change my code so that it can accept more "fuzzy" search results.

router.get("/", function(req, res){

    if (req.query.search) {

       Jobs.find({"name": req.query.search}, function(err, foundjobs){

       if(err){

           console.log(err);

       } else {

          res.render("jobs/index",{jobs:foundjobs});

       }

    }); 

    }

  Jobs.find({}, function(err, allJobs){

       if(err){

           console.log(err);

       } else {

          res.render("jobs/index",{jobs:allJobs});

       }

    });

});

1 Answer

0 votes
by (107k points)
edited by

I think you can use regex in MongoDB. The following is the code for what you're looking for (escapeRegex function source here):

function escapeRegex(text) {

    return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");

};

router.get("/", function(req, res) {

    if (req.query.search) {

       const regex = new RegExp(escapeRegex(req.query.search), 'gi');

       Jobs.find({ "name": regex }, function(err, foundjobs) {

           if(err) {

               console.log(err);

           } else {

              res.render("jobs/index", { jobs: foundjobs });

           }

       }); 

    }

}

With the help of package like search-index for search can help you to optimize your application's performance, with the added benefit of searching word stems (like returning "found" from "find").

If you want to learn full-stack web development in detail, this Full Stack Developer Course is the perfect fit for you.

Related questions

0 votes
1 answer
asked Feb 19, 2020 in Web Technology by ashely (50.2k points)
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Feb 9, 2020 in Web Technology by ashely (50.2k points)
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...