I want to search data by id and i try do like this
_id: { $regex: '63a1bda46ec7f02cf5e91825', $options: 'i' },
})
.populate('user', 'name')
.sort({ updatedAt: -1 });
but i got an error like this
Error: Can't use Options
and then i delete the options and i got
Error: Can't use $regx
CodePudding user response:
From the docs:
$regex
Provides regular expression capabilities for pattern matching strings in queries. MongoDB uses Perl compatible regular expressions (i.e. "PCRE" ) version 8.42 with UTF-8 support.
The regex you are using '63a1bda46ec7f02cf5e91825'
is a 24-byte string, and ObjectID is stored as 12 binary bytes (see https://bsonspec.org/spec.html), so a regular expression will never match an ObjectID.
The 'Error: Can't use $regex' is coming from Mongoose, not mongod. In your javascript you might be able to use the RegExp constructor like:
new RegExp('^' query '.*')
However that will still not permit matching an ObjectId with a regex.