I'm working on a Laravel API with a MongoDB database using jenssegers/laravel-mongodb .
I'm trying to make a filter to get some particular data using a regex. In the tutorial for this plugin I found this:
User::where('name', 'regex', new MongoRegex("/.*doe/i"))->get();
So my code looks like this:
School::where('name', 'regex', new MongoRegex("/haags/i"))->get();
But the result is empty. When I output the query it looks like this:
db.schools.find({"name":{"$regex":{"regex":"haags","flags":"i"}}})
And when I use that query in the console it says:
error: {
"$err" : "Can't canonicalize query: BadValue $regex has to be a string",
"code" : 17287
}
I also tried:
School::where('name', 'regexp', "/haags/i")->get();
But that gave me this query:
db.schools.find({"name":{"$regex":"\/haag\/i"}})
which apparently escapes the forward slash and makes the regex invalid. And besides that, a regex should not be between quotes or it should be something like this (found in the MongoDB manual):
db.products.find( { description: { $regex: /^S/, $options: 'm' } } )
So there is a problem in the conversion to MongoDB query or I'm doing something wrong. Can someone please tell me what it is?
I found the issue : It is actually siuated in the function compileWhereBasic in class Builder.
When the where condition has 3 parameters, the middle operator is appended in the front
Like {$regexp => { $regexp : "a", $options : "i"}} The first "$regexp" is the operator being apended. However this is not the case for = (already managed properly) and regexp that should not be appended.
Correction is like this :
if (! isset($operator) or in_array($operator, ['=','regex']) ) {
$query = [$column => $value];
} elseif (array_key_exists($operator, $this->conversion)) {
$query = [$column => [$this->conversion[$operator] => $value]];
} else {
$query = [$column => ['$' . $operator => $value]];
}
Instead of original code :
if (! isset($operator) or $operator == '=') {
$query = [$column => $value];
} elseif (array_key_exists($operator, $this->conversion)) {
$query = [$column => [$this->conversion[$operator] => $value]];
} else {
$query = [$column => ['$' . $operator => $value]];
}
Hope that helps !
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.