【问题标题】:Trying to do a search query via a GET request in Node.js and MongoDB尝试通过 Node.js 和 MongoDB 中的 GET 请求进行搜索查询
【发布时间】:2019-10-24 12:46:11
【问题描述】:

我使用 Node.js 和 MongoDB 在我的 REST API 中有以下函数,我正在构建它来进行搜索:

exports.searchPhone = async (req, res, next) => {
    try {
        const phoneNumber = req.query.phone;
        const locations = await Location.find({
            phone: phoneNumber 
        });
        res.json(locations);
    } catch (err) {
        next(err);
    }
};

我的回复没有任何错误,但我也没有得到任何结果,尽管我传递了一个我知道数据库中存在的电话号码。

谁能看出我做错了什么?

【问题讨论】:

  • console.log(locations) 是否正在打印???还要检查您的phoneNumber 打印是否正确;y
  • 也可以尝试在你的catch中添加一个控制台console.log(err)
  • @Subburaj 非常感谢您的评论。我想我在这里看到了我的问题。我在 MongoDB 中的电话号码作为字符串值存储为“+123456789”,因此当我在请求中传递电话参数时,我也将其作为“+123456789”发送。但是,当我执行 console.log(phoneNumber) 时,我对控制台的输出是:123456789(即没有 + 号)。我该如何纠正这个问题?
  • @syedfa 你可以只连接字符串phoneNumber = "+" + phoneNumber 并在查询中传递它
  • @syedfa 你可以使用trim 函数来解决这个问题。使用可以如下使用phoneNumber = "+" + phoneNumber.trim()

标签: node.js mongodb rest


【解决方案1】:

如下更改查询:

phoneNumber = "+" + phoneNumber.trim()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-30
    • 2019-02-27
    • 2021-04-07
    • 2022-01-06
    • 2016-05-21
    • 1970-01-01
    • 1970-01-01
    • 2020-12-23
    相关资源
    最近更新 更多