skip to Main Content

I am desperately looking for a way to give a String and make it case-insensitive, and get the result with MongoDB.
I tried with a RegEx, but it doesn’t work properly, because if the given String has some characters, they can conflict with the RegEx.

I saw that MongoDB allows to do this, but without RegEx, which seems better, with $caseSensitive, except that I don’t understand how this works.

Can you help me please?

What I used to do:

const user = await userModel.findOne({ Name: new RegExp("\b" + request.username.toString().trim() + "\b", "i"), Password: hash });

Thank you in advance for your answer!

2

Answers


  1. Best option is to create case insesitive index

    Example:

       db.collection.createIndex( { Name: 1},
                      { collation: { locale: 'en', strength: 2 } } )
    

    And search insensitive as follow:

     db.collection.find( { Name: "JohN" } ).collation( { locale: 'en', strength: 2 } )
    

    Will find: John,joHn,JOHN etc.

    Login or Signup to reply.
  2. I think you should make use of $regex with i as option, just like this , read more here Mongo Documentation

    const user = await userModel.findOne({ Name :{regex:/request.username.toString().trim()/i}, Password: hash });
    

    It should work fine!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search