P
Prisma3d ago
ly7vs

Is my way the most optimal in this case ?

So based on my research previously if you wanted to delete an element from an array, you'd have to get the array first with a separate call then filter it with javascript, however I did notice new ways popping up but none of them seemed to work with me (I think because the array isn't an array of a certain model?). This is my model: model Wishlist { id Int @id @default(autoincrement()) userId Int @unique books String[] //book ids user User @relation(fields: [userId], references: [id]) } And this is my code, is there a way to make it more optiomal (prefer 1 call to the database instead of 2): //even thought it's a delete method, we are updating under the hood (since each user should have a wishlist) export async function DELETE( req: NextApiRequest, { params }: { params: Promise<{ userId: string }> } ) { try { const { userId } = await params; const { bookId } = req.body; const user = await prisma.user.findUnique({ where: { id: Number(userId) }, include: { wishlist: true }, }); const currentWishlist = user?.wishlist; if (currentWishlist) { const updatedBooks = currentWishlist.books.filter((id) => id !== bookId); const updatedWishlist = await prisma.wishlist.update({ where: { userId: Number(userId) }, data: { books: updatedBooks }, }); return Response.json(updatedWishlist, { status: 200 }); } else { return Response.json({ error: "Wishlist not found" }, { status: 404 }); } } catch (error) { return Response.json({ error: "Internal Server Error" }, { status: 500 }); } }
4 Replies
Prisma AI Help
You selected to wait for the human sages. They'll share their wisdom soon. Grab some tea while you wait, or check out #ask-ai if you'd like a quick chat with the bot anyway!
Nurul
Nurul3d ago
Hey 👋 Did you consider using the set attribute to set books array? https://www.prisma.io/docs/orm/reference/prisma-client-reference#set-1 Your approach is fine. There is a feature request to provide an inbuilt way to update scalar lists here: https://github.com/prisma/prisma/issues/7401 I would recommend adding a 👍 to it so that our product team can prioritise it.
ly7vs
ly7vsOP3d ago
Thank you, so by using set i can cut a few lines of code, but I still need to use 2 seperate calls right ?
Nurul
Nurul3d ago
That's correct

Did you find this page helpful?