I am using this in my code and getting an error
const searchKey = req.params.key;
const user = await User.find({
'$or': [
{ name: { $regex: searchKey } },//Type String
{ phone: { $regex: searchKey } }, //Type Number
{ email: { $regex: searchKey } }//Type String
]
});
Getting Error
"stack": "CastError: Cast to number failed for value "99" (type string)
API URL = http:localhost/search/abc
API URL = http:localhost/search/999
2
Answers
The error is occurring because the
phone
field is a number, but thesearchKey
variable is a string. When the$regex
operator is used on a number field, the value being searched for must also be a number.To fix the error, you can either convert the
searchKey
variable to a number before using it in the query, or you can modify the query to use the$eq
operator instead of the$regex
operator for thephone
field.To convert the
searchKey
variable to a number, you can use theNumber()
function:To modify the query to use the
$eq
operator instead of the$regex
operator for the phone field, you can change the following line:To this:
The
$eq
operator will compare the value of thephone
field to the value of thesearchKey
variable. If the values are equal, the document will be returned in the results.Once you have made one of these changes, the error should be fixed.
The mongodb $regex
This means you can’t use it on fields with Number datatype, period.
To me, it doesn’t make any sense to do a pattern match on phone numbers unless you are trying to search area codes or something. If that’s the case then you could store the
phone
field as a string equivalentphoneAsString
then the$regex
would work on that field. If you are just trying to make a hit on the phone number then simply refactor your query as follows: