AndrewLeonardi AndrewLeonardi - 4 months ago 13
jQuery Question

Fuzzy Searching with Mongodb?

I have managed to set up a search feature in my mongodb app. See the code below. This works very well however it only returns exact results. How would I change my code to make it accept more "fuzzy" search results? Thanks!

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});
}
});
});

Answer

UPDATE: I have learned that using regex in a query-based db search is extremely dangerous and makes your application vulnerable to a DDoS attack. I would recommend finding another solution, but don't know of one myself (besides libraries).


Original response:

I believe that to do "fuzzy" search you will need to use regex. This should accomplish what you're looking for:

router.get("/", function(req, res) {
    if (req.query.search) {
       const regex = new RegExp(req.query.search, 'i');
       Jobs.find({ "name": regex }, function(err, foundjobs) {
           if(err) {
               console.log(err);
           } else {
              res.render("jobs/index", { jobs: foundjobs });
           }
       }); 
    }
}

This is a simple regex, and if you want to escape special characters you will need something more complicated like the expression found here.

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