1

The query works in mongo console : db.blogs.find({title : /fun/i}); but I tried to use it in nodejs, it won't work if I do it as :

var keyword = "fun";

query = { "title" : "/"+keyword+"/i" }; //doesn't work

query = { "title" : /fun/i };  //works, but I need to use the variable name - keyword

1 Answer 1

1

When dynamically creating a regular expression, you need to use the RegExp constructor instead of the literal notation with the /chars:

var keyword = "fun";
var query = {title: new RegExp(keyword, "i")};
Sign up to request clarification or add additional context in comments.

Comments

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.