使用Next.js getServerSideProps获取单个登录用户数据问题求助
现有代码核心问题
getServerSideProps未获取next-auth登录会话,查询条件id属于未定义变量,无法定位目标用户findOne返回单条文档对象,无需调用toArray()方法,该方法仅适用于find()批量查询场景- 前后props传递不匹配:服务端返回的属性名为
users,组件接收参数为user,且单用户数据不需要map遍历 - 若数据库中
_id为MongoDB默认的ObjectId类型,直接传入字符串id会匹配失败,需要做类型转换
修复后代码
import { connectToDatabase } from '../../lib/mongodb'; import { ObjectId } from 'mongodb'; import { getServerSession } from "next-auth/next"; import { authOptions } from "../api/auth/[...nextauth]"; // 替换为你实际next-auth配置文件的导出路径 import Head from 'next/head'; import Sidebar from '../components/Sidebar'; export default function Dashboard({ user }) { return ( <> <Head> <title>Ellis Development - Dashboard</title> </Head> <Sidebar /> <section className="content dashboard-content"> <h1>Dashboard</h1> {user && ( <div> <h2>{user.firstname} {user.lastname}</h2> <p>{user.email}</p> </div> )} </section> </> ) } export async function getServerSideProps(context) { // 获取当前登录用户会话 const session = await getServerSession(context.req, context.res, authOptions); // 无登录会话直接重定向到登录页 if (!session) { return { redirect: { destination: '/login', permanent: false, }, }; } const client = await connectToDatabase(); // 注意:如果你的next-auth会话中存储的是邮箱,查询条件改为 {email: session.user.email} 即可 const user = await client.db().collection('users').findOne({ _id: new ObjectId(session.user.id) }); return { props: { user: user ? JSON.parse(JSON.stringify(user)) : null } } }
注意事项
- 请将代码中
authOptions的导入路径替换为你项目中next-auth配置文件的实际路径 - 如果你在next-auth的会话中存储的用户标识是邮箱而非id,将查询条件替换为
{email: session.user.email}即可,不需要做ObjectId转换
内容的提问来源于stack exchange,提问作者Ben Bagley
相关产品推荐
相关产品推荐

