Title
f

femzy

02/02/2022, 7:44 PM
I am building a shopping cart app using nodejs, mysql and prisma My model
model User {
  id          Int @id @default(autoincrement())
  name        String
  email       String @unique
  password    String
  createdAt   DateTime @default(now())
  products    Cart[]

  @@map("users")
}

model Product {
  id          Int @id @default(autoincrement())
  name        String @unique
  description String
  price       Int
  stock       Int
  sku         String
  createdAt   DateTime @default(now())
  Category    Category? @relation(fields: [categoryId], references: [id])
  categoryId  Int
  users  Cart[]

  @@map("products")
}

model Category {
  id          Int @id @default(autoincrement())
  name        String @unique
  products    Product[]
  createdAt   DateTime @default(now())

  @@map("categories")
}

model Cart {
  id  Int   @id @default(autoincrement())
  user User @relation(fields: [userId], references: [id])
  userId  Int
  product Product @relation(fields: [productId], references: [id])
  productId Int
  quantity  Int
}
I made the Cart table a join table due to the User and Product having a Many-to-Many relationship My Routes
router.get("/", async (req, res) => {
  try {
    const cart = await prisma.cart.findMany({
      include: { product: true },
    });
    res.status(200).json(cart);
  } catch (error) {
    res.status(500).json(error);
  }
});

// Fetch a user's cart
router.get("/:userId", async (req, res) => {
  try {
    const cart = await prisma.cart.findOne({
      where: { userId: req.params.userId },
      include: { product: true },
    });
    res.status(200).json(cart);
  } catch (error) {
    res.status(500).json(error);
  }
});

<http://router.post|router.post>("/", async (req, res) => {
  try {
    const cart = await prisma.cart.create({
      data: req.body,
    });
    res.status(200).json(cart);
  } catch (error) {
    res.status(500).json(error);
  }
});

module.exports = router;
My route to fetch a user's cart is not working, please what could be the problem and any advice to make the app better would be appreciated
m

Maciek K

02/03/2022, 10:59 AM
You would need to make
userId
field on
Cart
@unique
in order to use it in the where clause. Also it should be
findUnique
, not
findOne
.
f

femzy

02/03/2022, 12:07 PM
Thanks