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();
};
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.
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 .
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.
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") } }
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With