Search code examples
javascriptnode.jsregexmongodbmongoose

Regex is not working as expected in MongoDB


I am using MongoDB as a database. And for some use cases, I need to search by email address. So the user will enter some text (maybe a complete or incomplete email address), and then I need to filter the document. I am using regex for filtering.

if (search) {
    regex = new RegExp(search, 'i');
}

And query looks like this

query: {
       ...(search && {
           $or: [
               { 'user.firstName': regex },
               { 'user.lastName': regex },
               { 'user.email': regex },
           ],
       }),
   }

But it is not fetching anything. Even I tried it using MongoDB Compass but it didn't work. You can see prashant.singh+07/[email protected] exists in the DB.

enter image description here

But when I write the same as the search query it didn't work

{"project._id" : ObjectId('6438ccea78ceb75cf48fced8'), "user.email" : {$regex : 'prashant.singh+07/[email protected]', $options : "i"}}

It results in nothing.

enter image description here


Solution

  • The problem is that your regex pattern is invalid and contains symbols with special meanings in Regex.

    Paste your regex pattern in Regex101 and you will find that it is invalid because it contains unescaped \ character.

    While these symbols have special meanings in Regex:

    . - Match any character

    + - Match previous token with one or unlimited times

    In order to fix your regex, you should escape these characters with a \ (backslash).

    prashant\.singh\+07\/04@testunity\.com
    

    Demo @ Regex 101

    While in JS wise, make sure that the input is escaped for the Regex characters before filtering via the function below:

    function escapeRegExp(string) {
      return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); // $& means the whole matched string
    }
    
    if (search) {
        regex = new RegExp(escapeRegExp(search), 'i');
    }
    

    Reference: Escaping (section) Regular expressions - JavaScript | MDN