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

从Node.js与MongoDB获取API数据时返回空数组问题求助

Node.js + MongoDB API 返回空数组问题排查与解决

问题背景

使用Node.js结合MongoDB开发API时,前端调用接口返回空数组,但数据库中存在对应数据,其他API可正常工作。

后端代码

router.get('/:producttype',async(req,res)=>{
  mongoose2.connect(dbUrl)
  try{
    let users = await equipementModel2.find({producttype: req.params.producttype})
    res.send({
      statusCode:200,
      users
    })
  }
  catch(error){
    console.log(error)
    res.send({statusCode:400,message:"Internal Server Error",error})
  }
})

前端代码

function Allproducts() {
    let getproducts = async (producttype) => {
          
          let res = await axios.get(`http://localhost:4000/users/${params.producttype}`)
          console.log(res)
          
          if (res.data.statusCode === 200) {
            setData(res.data.users)
          }
          else {
            alert(res.data.message)
          }
        }
      
        useEffect(() => {
          getproducts()
        }, [])
}

export default Allproducts

排查与解决方案

1. 前端请求参数错误

  • 前端getproducts函数声明接收producttype参数,但调用时未传入;同时请求URL中使用的params.producttype未定义,无法获取正确参数值。
  • 修复方案:
    • 若从路由参数获取producttype,需先通过useParams()获取:
      import { useParams } from 'react-router-dom';
      
      function Allproducts() {
        const params = useParams(); // 初始化路由参数
        
        let getproducts = async () => {
          let res = await axios.get(`http://localhost:4000/users/${params.producttype}`)
          // 其余逻辑不变
        }
        
        useEffect(() => {
          getproducts()
        }, [params.producttype]) // 添加参数依赖,参数变化时重新请求
      }
      
    • 若为固定类型,直接传入对应值:getproducts('目标类型')

2. 后端数据库连接逻辑错误

  • 每次请求都调用mongoose2.connect(dbUrl),可能导致查询执行时数据库连接未就绪,返回空结果。
  • 修复方案:将数据库连接移至路由外,仅初始化一次(如项目入口文件):
    // 入口文件(如app.js)
    mongoose2.connect(dbUrl)
      .then(() => console.log('数据库连接成功'))
      .catch(err => console.error('数据库连接失败', err));
    
    // 路由文件中移除connect代码
    router.get('/:producttype',async(req,res)=>{
      try{
        let users = await equipementModel2.find({producttype: req.params.producttype})
        res.send({
          statusCode:200,
          users
        })
      }
      catch(error){
        console.log(error)
        res.send({statusCode:400,message:"Internal Server Error",error})
      }
    })
    

3. 查询条件不匹配

  • 数据库中producttype字段的大小写、拼写可能与请求参数不一致,导致查询无结果。
  • 修复方案:
    • 统一字段名与参数的大小写、拼写;
    • 若需不区分大小写查询,使用正则表达式:
      let users = await equipementModel2.find({
        producttype: { $regex: new RegExp(req.params.producttype, 'i') }
      })
      

4. 前端状态渲染问题

  • 需确保setData正确更新状态,且组件在状态变化时重新渲染。
  • 示例渲染逻辑:
    return (
      <div>
        {data.length > 0 ? (
          data.map(item => <div key={item._id}>{item.name}</div>) // 根据实际字段调整
        ) : (
          <p>暂无数据</p>
        )}
      </div>
    )
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 11:10:37