Muhammad Usman
Muhammad Usman

Reputation: 10148

Search in Mongodb passing variable (search terms) from API

I am using Nodejs and Mongodb. I've written an API to return documents against searched property, I've managed to return all the results containing the searched terms. This is the code that I am using

collection.find({ "phone": new RegExp(req.params.phone, 'i') }, function (err, task) {
    if (err)
      res.send(err);
    res.json(task);
  }); 

Everything seems to work fine but when I search with string starting with + I get the following exception

Invalid regular expression: /.*+.*/: Nothing to repeat.

This seems to be a problem with what I am creating my regex expression and I am not so good with regex.

Any help would be appreciated

Thanks

Upvotes: 1

Views: 64

Answers (1)

antoni
antoni

Reputation: 5546

I think you need to escape the + character with \ (see here) as it is used in regex to repeat a pattern at least once.

  • .* means repeat anything 0 times or more
  • .+ means repeat anything 1 time or more
  • .*+ breaks

hope it solves your current problem, but also note that your regex is very loose and can capture anything even special chars & whitespaces.

Upvotes: 2

Related Questions