Case-insensitive query check - MongoDB

Hi, I would like to check the name a user enters. If it is already taken the code will give this message:

 if (names.findOne({name:name.value})) {
    template.$('.errorPopUp').text("Name already taken.")

This works in a primitive way - however, it’s not case-sensitive. So being give a name “test”, it would go through with a new name being “Test”. Could someone explain to me, how to make this query case sensitive?

Many thanks!

names.findOne({name: new Regexp(name.value, 'i')})

basically use use an insensitive regular expression, if you aren’t sure where test appears in the string, use ‘ig’ to search it (g)lobally in the string.

1 Like

Thank you, however, it gave me reference error with this syntax:

However, this worked:

if (Characters.findOne({ name: {$regex: name.value, $options: 'i'} })) 

Ah yes, I was thinking about building an aggregation. Glad you figured it out.

Another technique for case-insensitive querying is creating a collation index.

await names.rawCollection().createIndex( 
  { name: 1 },
  { collation: { locale: 'en_US', strength: 2 } }

await names.find({ name })
  .collation({ locale: 'en_US', strength: 2 })

Yeah, creating index would be best, Regex can be very expensive.

There are still some traits about this way that makes it not usable for me.

if (Characters.findOne({ name: {$regex: name.value, $options: 'i'} })) 

Given a name “Timo” entered the collection, this query will not allow a “Tim” as name or even a “T”. Why is that?

You may want to learn more about how regex works. Adding the g flag would find timo if searching tim. It would also find things like asdftimo if adding the g flag.

You could do ^tim.* To find things that start with tim and have any amount of characters after but then again there are a ton of use cases that you will know. Try using the site to experiment.

But as far as I understood I only added the i-flag? I mean, when I test it with the same condition on regex101, it’s not giving me any result. Thats why I’m confused.

I had the i-flag tested on regex101 and being “Kuroki” the string it didn’t match with “Kuro”

This really comes down to understanding how regex works, here is an example:

Do you see I have g and I used as flags?

i - is case insensitive,
g - is search anywhere in the string for the match

see here:

for this it doesn’t match because it isn’t using the g.

You need to learn regex a little more, and as a programmer/developer I suggest you learn it a lot more since it is very powerful and can do a lot more.

Can you please help me to use mongodb collation feature on meteor server code