【问题标题】:API call using Mongoose .find() with filter not returning anything?使用带有过滤器的 Mongoose .find() 调用 API 不返回任何内容?
【发布时间】:2020-07-19 06:08:31
【问题描述】:

今天开始发生最奇怪的事情。使用 Mongoose/Node 的其他工作 API 调用突然停止返回结果。我也在 Insomnia 中测试了调用,没有返回数据,但也没有错误。正如我所提到的,它之前工作过......这是 Node 和 React 块:

Node.js:

router.route('/top/:category').get((req, res) => {
    Whiskey.find({ category: req.params.category }).sort({ rated: -1 }).limit(3)
        .then(whiskies => res.json(whiskies))
        .catch(err => res.status(400).json('Error: ' + err));
});

React Hook 调用它:

useEffect(() => {
        console.log(`http://localhost:5000/whiskies/top/${capitalize(category)}`)
        axios.get(`http://localhost:5000/whiskies/top/${capitalize(category)}`)
            .then(res => {
                if (res.data.length > 0) {
                    setWhiskies(res.data)
                    console.log(res.data)
                } else {
                    console.log("No items")
                }
            })
    }, [])

我在尝试调试时发现的一些东西:如果您从 .find() 中删除过滤器,则 API 调用有效。我也没有在前端更改任何有关通话的内容。

【问题讨论】:

  • 请检查您的MongoDB服务状态是否正在运行。
  • 是的。正如我所提到的,API 调用没有过滤器。

标签: node.js mongodb mongoose mongodb-query mongoose-schema


【解决方案1】:

我认为问题在于这一行,${capitalize(category)}

您将 url 中的类别名称大写并将其发送到节点 api。

请按原样发送category,或在后端将其转为小写,然后再提交给查询。

使用以下内容。

let categoryName = req.params.category;
Whiskey.find({ category: categoryName.toLowerCase() }).sort({ rated: -1 }).limit(3)

希望这会奏效。谢谢

【讨论】:

    猜你喜欢
    • 2018-10-02
    • 2010-11-20
    • 2019-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-26
    • 2022-12-15
    相关资源
    最近更新 更多