1

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,

9
  • try to put word.replace(/\./g, '\\\\+') instead Commented May 25, 2018 at 8:16
  • RegExp - no need to escape strings when you use that. Commented May 25, 2018 at 8:19
  • You should be able to do /[.+]/g, '\\+'... Commented May 25, 2018 at 8:23
  • 1
    @Ashish I did that only for both + and .. But, didn't work Commented May 25, 2018 at 8:47
  • 1
    My original code worked. Actually the bug was with different part of code. In the request only, it was coming as c insead of c++ because the browser was omitting the +. Fixed that issue. Thanks for your response. :) Commented May 25, 2018 at 8:57

1 Answer 1

2
let word = "c++";

Skill.find({ "name": RegExp("^" + word.replace(/\+/g,"\\+"),"i") })

or

Skill.find({ "name": { "$regex": "^" + word.replace(/\+/g,"\\+"), "$options": "i" } })

Both return the document without problem

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your answer. The code was fine. issue was with the request parameter where it was coming as c instead of c++. Browser was the culprit.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.