CRUD With Prisma Client
Prisma Fundamentals
Chapter 5 ยท CRUD With Prisma Client
With a schema and a database in place, it's time to use them. This chapter covers the four basic operations — Create, Read, Update and Delete — using the blog schema from Chapter 3, plus how to handle the errors Prisma throws and how to look at your data with Prisma Studio.
prisma.user.create(...), prisma.post.findMany(...),
and so on. Each takes one object of options, such as where, data and select,
and every one returns a Promise, so use await. Your editor's autocompletion will show exactly which
options each method accepts.
Create
TypeScript checks the data object against the schema: leave out a required field such as
slug, or misspell one, and it won't compile. Fields with defaults (id,
published, createdAt) can be left out.
createMany accepts skipDuplicates: true to quietly skip rows that would break a unique
rule, but SQLite, SQL Server and MongoDB don't support it. On those, check first or insert one at a time.
Read
| Method | Returns | Use when |
|---|---|---|
findUnique | One record or null | Looking up by the ID or another @unique field |
findUniqueOrThrow | One record, or throws an error | The record must exist |
findFirst | The first match or null | Searching by any field, where several might match |
findFirstOrThrow | The first match, or throws | As above, when a match must exist |
findMany | An array (possibly empty) | Lists of records |
count | A number | How many records match |
prisma.post.findUnique({ where: { title: "Hello" } }) won't compile, because title
isn't unique — the database could return several rows. Use findFirst or findMany
for non-unique fields. Chapter 6 covers where in depth.
Choosing fields: select
Update
viewCount, adding 1 in your code, and saving it back can lose counts: if two visitors
arrive at the same moment, both read 5 and both save 6. { increment: 1 } asks the database to do the
addition itself, so both visits are counted. There are also decrement, multiply,
divide and set.
Upsert: update or create
Delete
prisma.post.deleteMany({}) — or updateMany with no where — affects
every row in the table. It's occasionally what you want (clearing test data), and a disaster when it isn't.
Handling Errors
When the database rejects an operation, Prisma throws a PrismaClientKnownRequestError with a
code that tells you why. Two you'll meet constantly:
| Code | Meaning | Typical cause |
|---|---|---|
P2002 | Unique constraint failed | Creating a user with an email that already exists |
P2025 | Record not found | update or delete on a record that doesn't exist; the ...OrThrow methods |
Looking at Your Data: Prisma Studio
This opens a browser-based table viewer on your own machine, where you can browse, filter, add, edit and delete rows without writing any code. It's ideal for checking what your scripts actually did.
Hands-On Exercises
Write a script that creates three posts with createMany, publishes one of them, counts the drafts, and then prints just the titles of all posts. Check the results in Prisma Studio.
Write a function registerUser(email, name) that returns a friendly message instead of crashing when the email is already taken, and a function recordView(slug) that increments a post's view count and returns null if the post doesn't exist.
For each task, pick the best method and explain why: (a) show one post from its URL slug; (b) find the most recent unpublished post; (c) make sure an "about" page exists, creating it only if missing; (d) clear all posts before a test run.
๐ View solutionChapter 5 Quick Reference
- Every model has the same methods; each takes an options object and returns a Promise
- Create:
create,createMany(returns a count),createManyAndReturn(PostgreSQL, CockroachDB, SQLite) - Read:
findUnique(unique fields only),findFirst,findMany,count, and...OrThrowvariants selectfetches only the fields you name, and narrows the result type- Update:
update,updateMany,upsert; use{ increment: 1 }and friends for counters - Delete:
delete,deleteMany— an emptywhereaffects every row - Errors:
Prisma.PrismaClientKnownRequestError;P2002duplicate unique value,P2025record not found npx prisma studioopens a browser view of your data