0

I try to get data from mongoodb by querying find a field name. i use regular expression to get that data. for example if set const name = 'st' then i will get 'steven','stephanie','stella'.

      const name = req.params.str;
      const user = await User.find({ "name": {$regex:`/${name}/`}});
      console.log(user);

i try the code above and the result is null

  • Please check https://stackoverflow.com/questions/26699885/how-can-i-use-a-regex-variable-in-a-query-for-mongodb – Vinod Louis Mar 15 '21 at 08:24
  • 3
    Does this answer your question? [How can I use a regex variable in a query for MongoDB](https://stackoverflow.com/questions/26699885/how-can-i-use-a-regex-variable-in-a-query-for-mongodb) – Kevin Wang Mar 15 '21 at 13:26

1 Answers1

0

You should use regex in a query like this:

var regex = /^someRegex/i; // It's a regex obj no double quote here
var query = { name: { $regex: regex } };
Murat Colyaran
  • 2,075
  • 2
  • 8
  • 27