Gerald Sihotang
Gerald Sihotang

Reputation: 275

Search number in MongoDB and NodejS

I have simple data like this in MongoDB

{
    "_id": "eE-sOpegt",
    "isApproved": true,
    "isDttotWarningFlagRaised": false,
    "fullname": "Gerald Bendryandre Sihotang",
    "email": "[email protected]",
    "password": "$2a$10$Uib2qpgLrzYAM4KmPdX/bOP6pBozJ6SDadCBSYoXY1JNcSJI7/3xC",
    "phone": 6281234567890,
    "registrationStep": 2,
    "role": "user",
    "__v": 0
}

See the phone, its a number NOT a string.
I want to search this data with one field using paginate
Here is the code:

User.paginate({
    $or: [
      { fullname: new RegExp('.*' + req.query.q + '.*', 'i') },
      { email: new RegExp('.*' + req.query.q + '.*', 'i') },

      /* Here is the problem 
         When I comment this phone, it works and return data.
         When its not commented, returns error
      */
      // { phone: {$eq: Number(req.query.q) } }
    ]
  }
...

I call this API using postman with this URL
localhost:8000/getUsersByQuery?q=gerald

It works when I comment the { phone }
But it returns error when the phone is not commented
How can I get the data with the phone number?

Upvotes: 0

Views: 598

Answers (1)

Viral Patel
Viral Patel

Reputation: 1156

Here in the Phone field you are passing string instead of number that's why its given error. So you need to check whether the first req.query.q is numeric or not. Then you need to pass it in Number().

Here you can use the below function for checking the same.

function isNumeric(num)
{ 
   return !isNaN(num)
}

Below is some Example of isNan function.

isNaN(num)         // returns true if the variable does NOT contain a valid number
isNaN(123)         // false
isNaN('123')       // false
isNaN('1e10000')   // false (This translates to Infinity, which is a number)
isNaN('foo')       // true
isNaN('10px')      // true

Upvotes: 1

Related Questions