ly7vs
ly7vs
PPrisma
Created by ly7vs on 3/7/2025 in #help-and-questions
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 }); } }
5 replies