skip to Main Content

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


  1. The error is occurring because the phone field is a number, but the searchKey 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 the phone field.

    To convert the searchKey variable to a number, you can use the Number() function:

    const searchKey = Number(req.params.key);
    

    To modify the query to use the $eq operator instead of the $regex operator for the phone field, you can change the following line:

    { phone: { $regex: searchKey } }
    

    To this:

    { phone: { $eq: searchKey } }
    

    The $eq operator will compare the value of the phone field to the value of the searchKey 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.

    Login or Signup to reply.
  2. The mongodb $regex

    Provides regular expression capabilities for pattern matching strings in queries.

    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 equivalent phoneAsString 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:

    // searchKey = 999
    const user = await User.find({
            '$or': [
                { name: { $regex: searchKey } },
                { phone: searchKey }, //Will match 999 but not 9 or 99 or 9999
                { email: { $regex: searchKey } }
            ]
        });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search