NextJS Prisma and MongoDB relation

21 Views Asked by At

I have a nextjs project with prisma and mongodb. It is a shopping list with a model User and a model ShoppingItem. The user has field "toBuyForUser", this should be an arrays of ShoppingItems. It also has a field "inCartForUser", should be an array of ShoppingItems too. I am struggling with the prisma.schema and need a little help.

Here I represent what I would like, but it is not working :

model User {
id             String       @id @default(auto()) @map("_id") @db.ObjectId
name           String?
hashedPassword String?
email          String?      @unique
emailVerified  DateTime?
image          String?
toBuyforuser   ShoppingItem[]
inCartforuser  ShoppingItem[]
}

model ShoppingItem {
id             String  @id @default(auto()) @map("_id") @db.ObjectId
name           String
image          String? 
toBuyForUser   User?   @relation(fields: [toBuyForUserId], references: [id], onDelete: Cascade)
toBuyForUserId String? @db.ObjectId
inCartForUser   User?   @relation(fields: [inCartForUserId], references: [id], onDelete: Cascade)
inCartForUserId String? @db.ObjectId
}

Also, I don't know how to handle CRUD operations. When creating a Shopping item, the fields toBuyForUser and inCartForUserId are not required. When clicking on a ShoppingItem, this should add the user ID in the "toBuyforUser". The same with "inCartforUser".

I hope this makes sense ! Thanks in advance.

0

There are 0 best solutions below