Reputation: 107
I come to you today because I have a little trouble. I am currently working on a csv import and transform the data into an object with models in the database. I send the API an object name and I made a $or for a search with plural or not:
if (req.query.name) {
params.$or = [
{name: { '$regex' : new RegExp(req.query.name+'(?!es|s|x)'), '$options' : 'ig' }},
{name: { '$regex' : new RegExp(req.query.name), '$options' : 'ig' }},
]
}
The problem is that if, for example, I send "boxes" and the model is called "Box (small)", it does not work. however if I send "box", it works. Could you enlighten me on my problem? it comes from the regexp.
EDIT : I would like to find the word "box" even if I send "boxes". Basically find the word whether plural or singular
Thank you in advance !
(Sorry for my English, I'm French)
Upvotes: 1
Views: 966
Reputation: 627536
You need to remove (?:es|[sx])
at the end of the search term (you may use .replace(/(?:es|[sx])$/, '')
) and add an optional group, not a negative lookahead:
new RegExp(req.query.name.replace(/(?:es|[sx])$/, '') + '(?:es|[sx])?')
See the regex demo.
The (?!es|s|x)
negative lookahead fails the match if the regex engine finds es
, s
or x
immediately after the req.query.name
value, while you want to optionally match a part of a string.
Upvotes: 1