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

NextJS:如何在getServerSideProps中传递MongoDB数据为Props

解决方案

你当前的代码存在两个关键问题:

  • 使用回调函数处理MongoDB查询,会导致getServerSideProps在查询完成前就执行return,无法拿到docs数据
  • getServerSideProps的参数不是userid,而是包含请求信息的context对象,用户ID需要从这个对象里提取(比如URL参数或查询参数)

修改后的代码如下:

export const getServerSideProps = async (context) => {
  await connectMongo();
  console.log("db connected on profile page");

  // 从context中获取用户ID,根据路由配置调整:
  // 动态路由 /profile/[userid] 用 context.params.userid
  // 查询参数 ?userid=xxx 用 context.query.userid
  const userid = context.params.userid;

  try {
    // 用await替代回调,等待查询完成后获取结果
    const userData = await User.findOne({ id: userid });
    
    return {
      props: {
        // 转换为普通JS对象,避免Mongoose文档对象的序列化问题
        user: userData ? JSON.parse(JSON.stringify(userData)) : null
      },
    };
  } catch (err) {
    console.log(err);
    return {
      props: {
        user: null,
        error: "Failed to fetch user data"
      },
    };
  }
};

关键说明:

  • 用await User.findOne(...)替代回调,确保查询完成后再执行后续代码,保证能拿到数据再返回props
  • 将Mongoose返回的文档对象转为普通JSON对象,避免Next.js序列化props时出现异常
  • 用try/catch捕获查询错误,返回兜底数据,防止页面崩溃
  • 必须从context对象中正确提取用户ID,匹配你的实际路由规则

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 05:52:44