【问题标题】:Search number in MongoDB and NodejSMongoDB 和 NodejS 中的搜索号
【发布时间】:2021-01-21 23:47:07
【问题描述】:

我在 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号码的数据?

【问题讨论】:

  • 你能分享一下错误吗?

标签: javascript node.js mongodb api mongoose


【解决方案1】:

在电话字段中,您传递的是字符串而不是数字,这就是给定错误的原因。 所以你需要检查第一个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

【讨论】:

    猜你喜欢
    • 2012-11-29
    • 2020-07-10
    • 2017-04-15
    • 2013-09-15
    • 1970-01-01
    • 2012-06-24
    • 1970-01-01
    • 2023-03-27
    • 2015-12-06
    相关资源
    最近更新 更多