You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Mongoose查询MongoDB无法获取collections数组:用户未找到问题及解决方案

问题分析与解决方案

问题根源

你遇到的核心问题是GET请求无法正确传递请求体参数:

  • 前端使用axios.get()时,第二个参数是请求配置对象(比如设置headers、URL参数等),并非请求体内容。所以你传入的{ email: localStorage.getItem("email") }并没有被放到请求体里,后端req.body.email拿到的是undefined。
  • 这导致你的MongoDB查询条件变成{ email: undefined },自然匹配不到任何用户,返回"User not found"错误。
  • 而你在updateOne中能正常找到用户,大概率是因为那个接口用的是POST请求,请求体参数能被后端正确解析。

解决办法

把GET请求改为POST请求,确保参数能通过请求体正确传递:

1. 修改后端路由(getCollections.js)

将router.get改为router.post,保持查询逻辑不变:

const router = require("express").Router();
const User = require("../models/user");
router.post("/", (req, res) => {
  var query = { email: req.body.email };
  User.find(query, (err, result) => {
    if (err) {
      res.json({ status: "error", error: "User not found" }, err);
    } else {
      res.json(result);
    }
  });
});
module.exports = router;

2. 修改前端请求代码

将axios.get改为axios.post,并把参数放到请求体的位置:

useEffect(() => {
  const url = "http://localhost:5000/api/getCollections";
  // const url = `https://item-collection-app-bz.herokuapp.com/api/getCollections`;
  axios
    .post(url, { email: localStorage.getItem("email") })
    .then((response) => {
      setListOfCollections(response.data);
    })
    .catch(err => {
      // 建议添加错误捕获,方便排查后续问题
      console.error("获取集合列表失败:", err);
    });
}, []); // 注意添加空依赖数组,避免组件重复渲染时频繁发送请求

额外优化建议

  • 给useEffect添加空依赖数组[],确保只在组件挂载时发送一次请求,避免不必要的重复请求。
  • 后端可以添加参数校验,比如先判断req.body.email是否存在,再执行查询,返回更明确的错误信息。

内容的提问来源于stack exchange,提问作者1zboro1

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 12:34:06