Home > Blockchain >  Case-insensitive with Mongoose
Case-insensitive with Mongoose

Time:06-10

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!

CodePudding user response:

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.

CodePudding user response:

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!

  • Related