In my user authentication I allow users to enter case insensitive email
. Recently I saw in the logs that one user can not authenticate himself. Reason is because his email
address has
character inside, and for some reason MongoDB case insensitive search can not find email with special characters. It's like the special characters are ignored when performing the regex search.
I created this testing example: Mongo Playground
What is the reason of this behavior and how to solve this?
CodePudding user response:
I solved it without $regex
, with aggregate
:
db.collection.aggregate([
{
"$match": {
"$expr": {
"$eq": [
{ "$toLower": "$email" },
{ "$toLower": "EXAMPLE @gmail.com" }
]
}
}
}
])
Yet, if someone have solution with $regex
, I would like to see that.
CodePudding user response:
If your users email have regex special characters like ,.,(,[
etc
You can escape them before searching else MongoDB will think you mean the escape character
Javascript code (from this answer)
function escapeRegExp(string) {
return string.replace(/[.* ?^${}()|[\]\\]/g, '\\$&');
}
With the above function would become \ and you could search like this
I am not sure i understanded but i think you need this.