I have a schema named Skills which has a single string field called name. I want to perform a search on the field based on a given string.
For normal strings like java, its working fine. But, for C++, its omitting the ++ part as + is a special character in regex. So I replaced + with \\+ which is working fine in mongodb.
To do this, following is my query in mongodb commandline which is giving me the required result:
db.skills.find({"name": {'$regex': '^c\\+\\+', '$options': 'i'}})
Following is my code with mongoose:
word = '^' + req.query.word;
word = word.replace(/\+/g, '\\+')
word = word.replace(/\./g, '\\+')
Skill.find({"name": {'$regex': word, '$options': 'i'}}).limit(10).exec(function (err, results) {
res.json({'results': results})
})
Here I have added the two replace statements to replace + with \\+ and . with \\.
But, the above code is not working. It's giving me zero result. Please help me if I am wrong somewhere.
Thanks,
word.replace(/\./g, '\\\\+')insteadRegExp- no need to escape strings when you use that./[.+]/g, '\\+'...+and.. But, didn't workcinsead ofc++because the browser was omitting the+. Fixed that issue. Thanks for your response. :)