mongoose: Regex: Error: Can't use $options with String

As defined in the MongoDB documentation, the following syntax :

find(name: { $regex : 'abc', $options: 'i' } )

is correct.

However, I’ve got the error Can’t use $options with String

The same query works when I use directly the mongo shell. I’m using mongoose 2.3.10 and mongo 2.0

About this issue

  • Original URL
  • State: closed
  • Created 13 years ago
  • Reactions: 2
  • Comments: 16

Most upvoted comments

I’m having an almost identical issue, except that I’m using a variable:

x = 'abc'
find({name: { $regex : x, $options: 'i' }} )

and getting the same error. I had to solve it with:

find({ name: new RegExp(x, 'i')}})

just pass a RegExp directly:

find(name: { /abc/i } )

+1 for this

I’m using $.ajax to send a JSON to a nodejs server with connect bodyParser middleware.

But it’s very hard/impossible to serialize a RegExp to JSON to send over a POST request.

    $.ajax({
      url: "/db/find/Users/"
      dataType: 'json',
      type: 'post',
      data: JSON.stringify({where : {name : /example/i} }),
      contentType: 'application/json; charset=utf-8',
      async : false,
      success: function(data){
      }
    });

The problem here is if I JSON.stringify a RegExp it returns an empty object. Having the ability to use $options in this scenario is very welcome.

JSON.stringify({where : {name : { $regex : "example", $options : "i"} } })