简体   繁体   中英

How do I access the default ObjectId MongoDB creates with NextAuth

I'd like to push data to the MongoDB document of the user currently logged in.

From what I understand, when you sign in with Twitter (for example), Next Auth creates a new: user, account, and session for that login. And using the useSession() hook, you can access the email, image, and name of the user, but not the ObjectId that MongoDB creates for you.

That's a problem for me because I need to make requests to my server that use the _id value of the user currently logged in, for the PUT request URL. I'd like to use the _id value mongo provides you instead of adding one with something like uuid.

Is there any way to do this?

I recently ran into this issue and found that using the callbacks option in [...nextauth].js allows you to modify what is sent back to the client.

Portion of my [...nextauth].js:

export default async function auth(req, res) {
  return await NextAuth(req, res, {
    adapter: MongoDBAdapter({
      db: (await clientPromise).db("myFirstDatabase"),
    }),
    providers: [
      GoogleProvider({
        clientId: process.env.GOOGLE_CLIENT_ID,
        clientSecret: process.env.GOOGLE_CLIENT_SECRET,
      }),
    ],
    callbacks: {
      async signIn({ user, account, profile, email, credentials }) {
        return true;
      },
      async session({ session, token, user }) {
        session.user._id = user.id;
        return session;
      },
    },
  });

The async session function will return the user object that is stored in your db, so you can add the id to the user object of session.

I can now access it using the session hook like before, but this time have access to the _id.

<div>{session.user._id}</div>

Here is a link to the NextAuth site that goes more in-depth of the power of session: NextAuth

I think this answer is related to your issue, check it out!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM