使用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
相关产品推荐
相关产品推荐

