21


From node js, i trying to retrieve the documents based on the keyword with case-insensitive. When i try directly from the mongo db console , i am able to see the result.

db.users.findOne({"displayName":{$regex: /.*abc./, $options:"i"}})

But when i try the same in node js, i am getting empty result.

var selector = { "displayName": {$regex: "/.*abc./", $options:"i"}}

is this due to regular expression not in javascript.
Can anyone please help me in this.

1

3 Answers 3

33

The $regex value needs to be either the string pattern to match or a regular expression object. When passing a string pattern, you don't include the / delimitters like you're doing in your node.js code.

So either of these would work in node.js:

var selector = {"displayName": {$regex: ".*abc.", $options:"i"}}

OR

var selector = {"displayName": {$regex: /.*abc./, $options:"i"}}
Sign up to request clarification or add additional context in comments.

Comments

15

could you please try this one, It works for me.

var getValue = "abc";

db.users.findOne({ displayName: new RegExp(regexValue, "i") }, function(err, res) {
  if (err) {
    console.log(err);
  } else {
    console.log(res.length);
  }
});

1 Comment

this is the only one working for me "mongoose": "4.11.2"
5

In mongodb console try this query

db.users.findOne({"displayName":{$regex: ".*abc", $options:"i"}})

and in nodejs var selector = users.find({ "displayName": {$regex: ".*abc", $options:"i"}})

here users = is a collection name

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.