Reputation: 1021
I am using next-auth, next.js, and prisma.
I want to update the User
table, but only if the session token matches what is stored in the database. Prisma's documentation on CRUD (Related records) only provides examples how to create related records (Creating a user and posts at the same time). I only want to update a user if the session id is a match.
I would like to be able to do something like this, where the user is only updated if email + session id both match:
export default async (req: NextApiRequest, res: NextApiResponse<User>) => {
let email = req.query.email as string;
let sessionId = req.query.email as string;
let username = req.query.username as string;
let zipcodeId = req.query.zipcodeId as string;
const updatedUser = await prisma.user.update({
where: { email: email, sessionId: sessionId },
data: {
username: username,
zipcodeId: Number(zipcodeId),
},
});
res.status(200).json(updatedUser);
};
// schema.prisma
model Session {
id String @id @default(cuid())
sessionToken String @unique @map("session_token")
userId Int @map("user_id")
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
expires DateTime
}
model User {
id Int @id @default(autoincrement())
name String?
email String? @unique
emailVerified DateTime?
image String?
username String? @unique
accounts Account[]
sessions Session[]
votes Vote[]
zipcodeId Int? @map("zipcode_id")
zipcode Zipcode? @relation(fields: [zipcodeId], references: [id], onDelete: Cascade)
}
Upvotes: 1
Views: 2506
Reputation: 7618
You would need to use updateMany
in this scenario as the fields which have @unique
attribute can only be passed in where clause of update query.
Here's the query through which you could add condition of email and sessionId
const updatedUser = await prisma.user.updateMany({
where: {
email: '[email protected]',
sessions: {
every: {
id: '1',
},
},
},
data: {
username: 'username',
},
});
Upvotes: 0