首页 > 解决方案 > MongoDB 和 NodejS 中的搜索号

问题描述

我在 MongoDB 中有这样的简单数据

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

phone,它number 不是一个string
我想用一个字段搜索这些数据,paginate
代码如下:

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) } }
    ]
  }
...

我使用带有此 URL 的邮递员调用此 API
localhost:8000/getUsersByQuery?q=gerald

它在我评论时有效但是当没有评论{ phone }
时它返回错误 如何获取带有数字的数据?phone
phone

标签: javascriptnode.jsmongodbapimongoose

解决方案


在电话字段中,您传递的是字符串而不是数字,这就是给定错误的原因。所以你需要检查第一个是否req.query.q是数字。然后你需要传入它Number()

在这里,您可以使用以下功能进行检查。

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

下面是 isNan 函数的一些示例。

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

推荐阅读