使用服务器端道具 nextjs 获取单个用户

Getting an single user using server side props nextjs

我正在使用 nextjs 创建仪表板,并且我使用 next-auth 进行身份验证。

但是,我正在尝试在个人用户登录仪表板时呈现他们的数据,但不确定哪里出错了,我知道我必须使用 findOne 回调,但出于某种原因我无法获取 ID 或电子邮件。

这是我目前的情况

import { connectToDatabase } from '../../lib/mongodb';
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>

        { users.map(user => (
          <div key={user.id}>
            <h2>{user.firstname} {user.lastname}</h2>
            <p>{user.email}</p>
          </div>
        )) }
      </section>
    </>
  )
}

// get data from database using server side rendering and mongodb connection
export async function getServerSideProps() {
  const client = await connectToDatabase();
  const users = await client.db().collection('users').findOne({ _id: id }).toArray();

  return {
    props: {
      users: JSON.parse(JSON.stringify(users))
    }
  }
}

您可以使用 getSession 来处理服务器端身份验证。

查看参考以获取更多资源link

import { getSession } from "next-auth/react"
...
export async function getServerSideProps(ctx) {
  const session = await getSession(ctx) //pass context to authenticate create session
  const id = session.user.id //get id from session

  const client = await connectToDatabase();
  const user = await client.db().collection('users').findOne({ _id: id }) // No need to use toArray its returns only 1 object

  return {
    props: {
      user
    }
  }
}