Sikau

Prisma · Day 3 · about 30 min

CRUD with Prisma Client

create, findUnique, update, upsert and delete.

The four verbs

Create, read, update, delete — every app does them all day. Prisma Client has a method for each, and they all take a plain object.

The CRUD methods

import { PrismaClient } from "@prisma/client";

const prisma = new PrismaClient();

const lassi = await prisma.dish.create({
  data: { name: "Lassi", category: "drink", price: 90, veg: true },
});
console.log("created", lassi.id);

const momo = await prisma.dish.findUnique({ where: { name: "Momo" } });
console.log("found", momo?.price);

const updated = await prisma.dish.update({
  where: { name: "Momo" },
  data: { price: { increment: 10 }, tags: { push: "chef's pick" } },
});
console.log("updated", updated.price, updated.tags);

const tea = await prisma.dish.upsert({
  where: { name: "Ginger tea" },
  update: { price: 60 },
  create: { name: "Ginger tea", category: "drink", price: 60, veg: true },
});
console.log("upserted", tea.name);

await prisma.dish.delete({ where: { name: "Sel roti" } });
console.log("remaining", await prisma.dish.count());
  • Many at once: createMany, updateMany, deleteMany (they return { count }).
  • findFirst takes any filter; findUniqueOrThrow throws instead of returning null.

The rest of this lesson

  • findUnique versus findFirstexplain
  • Atomic number updatesexplain
  • Not found?predict
  • Pick the methodmatch
  • Your turnwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 15 lessons of Prisma