CRUD operations let you create, read, update, and delete data in your app. Prisma helps you do this easily with your database.
CRUD operations with Prisma in NextJS
Start learning this pattern below
Jump into concepts and practice - no test required
import { PrismaClient } from '@prisma/client'; const prisma = new PrismaClient(); // Create await prisma.modelName.create({ data: { /* fields */ } }); // Read await prisma.modelName.findMany(); await prisma.modelName.findUnique({ where: { id: value } }); // Update await prisma.modelName.update({ where: { id: value }, data: { /* fields */ } }); // Delete await prisma.modelName.delete({ where: { id: value } });
Replace modelName with your actual Prisma model name (like user or post).
Use await because Prisma operations are asynchronous.
await prisma.user.create({ data: { name: 'Alice', email: 'alice@example.com' } });
const users = await prisma.user.findMany();
await prisma.user.update({ where: { id: 1 }, data: { name: 'Alice Updated' } });
await prisma.user.delete({ where: { id: 1 } });
This program shows all four CRUD operations with Prisma on a user model. It creates a user, reads all users, updates the created user, then deletes it. Finally, it prints the results at each step.
import { PrismaClient } from '@prisma/client'; const prisma = new PrismaClient(); async function main() { // Create a new user const newUser = await prisma.user.create({ data: { name: 'Bob', email: 'bob@example.com' } }); // Read all users const allUsers = await prisma.user.findMany(); // Update the new user's name const updatedUser = await prisma.user.update({ where: { id: newUser.id }, data: { name: 'Bobby' } }); // Delete the user await prisma.user.delete({ where: { id: updatedUser.id } }); // Return all users after deletion const usersAfterDelete = await prisma.user.findMany(); console.log('Created User:', newUser); console.log('All Users:', allUsers); console.log('Updated User:', updatedUser); console.log('Users After Delete:', usersAfterDelete); } main() .catch(e => console.error(e)) .finally(async () => { await prisma.$disconnect(); });
Always disconnect Prisma client with prisma.$disconnect() to avoid open connections.
Use try/catch or .catch() to handle errors in async Prisma calls.
Make sure your Prisma schema is set up and migrated before running CRUD operations.
CRUD means Create, Read, Update, Delete data.
Prisma provides easy methods to do CRUD with your database.
Use async/await and proper error handling when working with Prisma.
Practice
prisma.user.create() method do in Next.js with Prisma?Solution
Step 1: Understand the method name
The methodcreate()is used to add new data in Prisma.Step 2: Match method to CRUD operation
Creating means adding new records, soprisma.user.create()adds a new user.Final Answer:
It adds a new user record to the database. -> Option AQuick Check:
Create method = Add new record [OK]
- Confusing create() with findMany() which reads data
- Thinking create() updates existing records
- Assuming create() deletes records
Solution
Step 1: Identify Prisma update syntax
Prisma usesupdate()withwhereanddatakeys to update records.Step 2: Check option correctness
Only prisma.user.update({ where: { id: 5 }, data: { name: 'Alice' } }) uses correct methodupdate()and proper keyswhereanddata.Final Answer:
prisma.user.update({ where: { id: 5 }, data: { name: 'Alice' } }) -> Option CQuick Check:
Update method uses where and data keys [OK]
- Using non-existent methods like modify(), change(), edit()
- Missing where or data keys in update()
- Passing id directly without where object
const users = await prisma.user.findMany({ where: { active: true } });
console.log(users.length);What will
console.log(users.length) output?Solution
Step 1: Understand findMany with where filter
ThefindMany()method returns an array of records matching thewherecondition.Step 2: Analyze the filter condition
Only users withactive: trueare returned, sousers.lengthis count of active users.Final Answer:
The number of active users in the database. -> Option DQuick Check:
findMany with where returns filtered array [OK]
- Thinking findMany returns undefined or error
- Ignoring the where filter effect
- Assuming it returns all users without filter
await prisma.user.delete({ id: 10 });Solution
Step 1: Check delete() method syntax
Prisma's delete() requires an object with awherekey specifying the record to delete.Step 2: Identify missing where key
The code passes{ id: 10 }directly, missingwhere: { id: 10 }.Final Answer:
Missing the 'where' key wrapping the id. -> Option AQuick Check:
Delete needs where key with id [OK]
- Omitting where key in delete()
- Using remove() which does not exist in Prisma
- Thinking id type must be string always
- Believing delete() can't be awaited
Solution
Step 1: Understand the upsert method
Upsert updates if record exists, else creates new one in Prisma.Step 2: Match use case to method
Since we want to update or create based on existence,upsert()fits perfectly.Final Answer:
prisma.user.upsert({ where: { email }, update: { email }, create: { email } }) -> Option BQuick Check:
Upsert = update or create [OK]
- Using update() alone which fails if user missing
- Using create() alone which fails if user exists
- Using findUnique() which only reads data
