Meteor: how to make case-insensitive .findOne () collection?

I am using the method of changing the username in the Meteor application that I am writing. Before accepting the changes, I want to check if the username exists. User names can contain upper and lower case, but they must be unique names regardless of the case. For example, bob and bob cannot exist together.

The problem is that I cannot figure out how to make collection.findOne() , which is case insensitive. For example, let's say I have a collection called Profiles, I would like to do something like this:

 newName = "bob"; //Assume "Bob" exists as a username in the Profiles collection; var isAlreadyRegistered = Profiles.findOne({"username": newName}); if (isAlreadyRegistered == null) { saveUsername(); }; 
+6
source share
3 answers

You can use regex.

 var isAlreadyRegistered = Profiles.findOne({"username": /^newName$/i }); 

Or you can also request this:

  var isAlreadyRegistered = Profiles.findOne({ "username" : { $regex : new RegExp(newName, "i") } } ); 
+13
source

There are two ways, and your mileage may differ from your best approach, but both are pretty terrible as MongoDB makes a β€œsensitive” match:

The first approach is to use $regex :

 Profiles.findOne({ "username": { "$regex": "^" + newName + "\\b", "$options": "i" }}) 

This matches the word and only the exact word from the beginning of the line is case insensitive. The problem here is that you are scanning the index.

The second approach is to use an aggregate:

 db.collection("profiles").aggregate([ { "$project": { "username": 1, "lower": { "$toLower": "$username" } }}, { "$match": { "username": newName }} ]) 

And you do it where, of course, newName already converted to lowercase.

The problem here is that there will be a $project across the pipeline. But it can be useful if you can $match .

Of course, I think that aggregate is only available on the server side, not through Minimongo, so this should be considered.

+2
source

As a solution to your primary use case, I suggest using two fields to store the username, not just one.

The username you enter must contain a lower registration string for the username. In another additional field, the initial case-sensitive version is stored.

Searches will be conducted in the "username" field with the search criteria below and also before use.

+1
source

All Articles