1

I'm trying to work with mongoose to implement a simple search feature that I plan to expand later.

Basically what I'm trying to do is take a search query from the user and put it inside the mongoose find() query, but I'm using the built-in " regular expression" way according to their documentation:

    MyModel.find({ name: /john/i }, null, { skip: 10 })

Here, john is a static value, when I try to place a variable instead it doesn't work.

    MyModel.find({ name: /req.query.name/i }, null, { skip: 10 })

How can I place a variable instead of the static content?

P.S: I tried using the JS regular expression and it did work but I want to do it the mongoose way.

    MyModel.find({ name: new RegExp(req.query.name, "i") }, null, { skip: 10 }) //this works
  • I don't think using a variable in a regex used by Mongoose would be any different than using a variable in a regex generally. Related? https://stackoverflow.com/questions/494035/how-do-you-use-a-variable-in-a-regular-expression – Félix Paradis Jul 04 '20 at 17:12
  • @FelDev Well, they are the same I was just asking if I can do it the Mongoose way as I like to know multiple methods for doing something – Mahmoud Ashraf Jul 04 '20 at 17:26

2 Answers2

3

You can use $regex of mongoose

MyModel.find({ name: {$regex: req.query.name, $options:'i'} }, null, { skip: 10 }) 
ibrahimijc
  • 301
  • 2
  • 9
1

In order to create a dynamic regex from a string the only option is using new RegExp as you did. There is no way to to it with the literal /../-method (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions).

However, in either case, the result will be a regex object — which will have the same methods and properties attached to them. Mongoose does not actually care which way you create the regex.

Instead of creating the regex in javascript you can let mongoose/mongodb do it, as Ibrahim's answer proposes.

eol
  • 15,597
  • 4
  • 25
  • 43