Reputation: 6883
I am trying to find matching name in the collection. And if matches, the query should be rejected.
I used regex to make case insensitive search(For example, GOD !== god) but still it should be omitted.
This works fine.
field = 'name';
query[field] = { '$regex': new RegExp(req.body[field], "i"), '$options': 'i' };
The issue is when i use part of the word, its also getting rejected. For example Super Administrator is inserted. Followed by inserting Administrator throws error as Administrator is part of Super Administrator.
How to write mongo db query for case insensitive search that will be for exact match. not for parts.
Thanks in advance.
Upvotes: 0
Views: 2737
Reputation: 3819
You could add start and end characters into your regex:
field = 'name';
query[field] = { '$regex': new RegExp('^' + req.body[field] + '$', "i"), '$options': 'i' };
That should eliminate partial matches.
Upvotes: 1