Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Meteor: How to do a case insensitive collection.findOne()?

Tags:

mongodb

meteor

I'm implementing a way for users to change their username in a Meteor app I am writing. Before accepting changes, I want to check if the username already exists. Usernames can contain upper and lowercase, but they must be unique names regardless of case. For example, bob and Bob cannot exist together.

The problem is that I can't seem to figure out how to do a collection.findOne() that is case insensitive. For example, say I have a collection called Profiles, I'd like to be able 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();
};
like image 204
Chanpory Avatar asked Apr 12 '14 08:04

Chanpory


People also ask

How does findOne work in MongoDB?

MongoDB – FindOne() Method. The findOne() method finds and returns one document that matches the given selection criteria. If multiple documents satisfy the given query expression, then this method will return the first document according to the natural order which reflects the order of documents on the disk.

What does findOne return MongoDB?

findOne() method returns a Promise that resolves to the first document in the collection that matches the query. If no documents match the specified query, the promise resolves to null .

Does findOne return promise?

Another way is to get Promise in findOne , as this doc said, . exec() gives you a fully-fledged promise. Even with Promise , to meet you requirement, the result could be returned through callback function.


1 Answers

Your can use regular expression.

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

Or you can query like this also :

 var isAlreadyRegistered = Profiles.findOne({ "username" : {
                     $regex : new RegExp(newName, "i") } }
               );
like image 136
Sumeet Kumar Yadav Avatar answered Sep 27 '22 16:09

Sumeet Kumar Yadav