javascript - 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
解决方案
在电话字段中,您传递的是字符串而不是数字,这就是给定错误的原因。所以你需要检查第一个是否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
推荐阅读
- javascript - 如何仅打印日期而不是完整日期?
- php - ErrorException 未定义索引:HTTP_X_REQUESTED_WITH
- python - 如何将 rpy2.robjects.vectors.DataFrame 转换为 csv?
- javascript - 在数组数组中按 id 查找对象的索引
- git - 如何避免将文件夹推送到 git repo
- visual-studio-code - (vscode) 更改 Tomorrow Night 主题使用的字体之一?
- python - ValueError:检查目标时出错:预期 dense_3 具有 2 个维度。但我指定dense_3 有1维
- reactjs - 如何使用 Apollo Graphql 客户端和 React 解决“TypeError:无法读取未定义的属性“参数”?
- android - Kotlin 循环泛型
- python-3.x - 使用 Try 进行 Web 抓取:除了:在 For 循环中