code_dummy123
code_dummy123

Reputation: 103

how to make case insensitive query using variable?

I already have a user with a username Kevin in my database. I want prevent new users to pick Kevin, kevin, KeViN, etc. as their username when creating an account. How do I modify my query to check if such user exists ignoring case-sensitivity?

def validate_username(self, username):
    if db.users.find_one({"username":username}):
        raise ValidationError("username is already taken")

Upvotes: 2

Views: 138

Answers (3)

Dĵ ΝιΓΞΗΛψΚ
Dĵ ΝιΓΞΗΛψΚ

Reputation: 5669

just put a "case-insensitive unique index" on the username field.

if someone enters an existing username, mongo will throw a duplicate key error which you can handle in your code and ask the user to enter another username.

you can create the index like this:

db.collection.createIndex(
    {
        username: "username_idx",
        unique: true,
        collation: {
            locale: "en",
            strength: 2
        }
    }
)

Upvotes: 1

Kuldeep Mishra
Kuldeep Mishra

Reputation: 4040

db.users.find({ "username" : { "$regex" : username , "$options" : "i"}});

or

db.users.find({'username':{'$regex' : '^username$', '$options' : 'i'}})

Upvotes: 1

Mahesh
Mahesh

Reputation: 36

Not sure if it’s available on mongo directly. as an alternative, add another field to your user document and while saving username convert it into lowercase and save the hash-code in hash-code field.

So username : Kevin , hashcode : (hashcode of “kevin”)

Next time when a user enters Username : KeViN , hashcode : (hashcode of kevin)

Not if you put a validation or unique key constraint on handcode.. it should solve it.

Upvotes: 1

Related Questions