How to set Unique value in mongodb using node express both uper and lower case

Viewed 20

Well I have already done in mongoose schema by setting my property with unique:true like below

mongoose.Schema({ userName: { type: String, unique: true }})

this time i want to do it through my router api's

User.findOne({userName: req.body.userName})

it only works when i enter same string as save already in database.like userName: ranatouseef but if i enter userName: ranaTouseef it fails, well regix don't work here like regix also have issue like that well if i search for userName: rana regix find it ranatouseef. well same goes for touseef to well my issu is find same string but without casesensitive, how can i do that.

1 Answers

In this case, you should set the username in lower case.

new User({ username: req.body.userName.toLowerCase() });
User.save()

And when you want retrieve it, use the toLowerCase method on the argument.

User.findOne({ userName: req.body.userName.toLowerCase() })

You should always avoid to duplicate your data in your DB. Here, you are about to save a string in lowercase and in uppercase. I don't know your use case but it makes no sense to me.

Also, my solution solves the issue of "RanaTouseef" and "ranaTouseef" being 2 unique username

Related