【问题标题】:Getting an single user using server side props nextjs使用服务器端道具 nextjs 获取单个用户
【发布时间】:2021-11-22 08:29:47
【问题描述】:

我正在使用 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))
    }
  }
}

【问题讨论】:

    标签: javascript reactjs mongodb next.js server-side-rendering


    【解决方案1】:

    您可以使用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
        }
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2022-08-17
      • 2021-10-28
      • 2020-11-15
      • 2022-07-05
      • 2015-05-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-18
      相关资源
      最近更新 更多