I was wondering what is the best practice to check if username is already registered. For example I sign up as Peter and I want to prevent other users from using:
you've got the idea. Should I use regex for case-insensitive query using MongoDB in PHP:
$username = 'Peter';
$db->users->count(['username' => new MongoDB\BSON\Regex('^'.$username.'\\b', 'i')]);
or should I store 2 versions of username, the original version and one lower case version for this purpose?
$username = strtolower('Peter');
$query = $db->users->count(['username_lowercase' => $username]);
if ($query > 0) {
echo 'This username is already used';
}
or is there any other approach?
Regarding performance, the best approach is always to test and never have prejudice.
A third approach would be to use a case insensitive index with unique constraint. See https://docs.mongodb.com/manual/core/index-case-insensitive/ and oh I've found a duplicate of your question how to index a username in mongo with case-insensitively?
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