Fuzzy Searching with Mongodb?

I believe that to do “fuzzy” search you will need to use regex. This should accomplish what you’re looking for (escapeRegex function source here):

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

router.get("https://stackoverflow.com/", 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 });
           }
       }); 
    }
}

That being said, your application can experience performance issues when querying mongo by regex. Using a library like search-index for search could help optimize your application’s performance, with the added benefit of searching word stems (like returning “found” from “find”).


UPDATE: My original answer included a simple regular exression that would leave your application vulnerable to a regex DDoS attack. I’ve updated with a “safe” escaped regex.

Leave a Comment