CRUD means Create, Read, Update, and Delete data. Prisma helps you do these actions easily with your database in a NestJS app.
CRUD with Prisma in NestJS
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).
Each method returns a Promise, so use await inside async functions.
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 NestJS service uses Prisma to create, read, update, and delete users. The example function shows how to call these methods and print results. It also demonstrates proper PrismaClient disconnection.
import { Injectable, OnModuleDestroy } from '@nestjs/common'; import { PrismaClient, User } from '@prisma/client'; @Injectable() export class UserService implements OnModuleDestroy { private prisma = new PrismaClient(); async createUser(name: string, email: string): Promise<User> { return this.prisma.user.create({ data: { name, email } }); } async getUsers(): Promise<User[]> { return this.prisma.user.findMany(); } async updateUser(id: number, name: string): Promise<User> { return this.prisma.user.update({ where: { id }, data: { name } }); } async deleteUser(id: number): Promise<User> { return this.prisma.user.delete({ where: { id } }); } async onModuleDestroy() { await this.prisma.$disconnect(); } } // Example usage (in an async context): async function example() { const service = new UserService(); const newUser = await service.createUser('Bob', 'bob@example.com'); console.log('Created:', newUser); const allUsers = await service.getUsers(); console.log('All users:', allUsers); const updatedUser = await service.updateUser(newUser.id, 'Bobby'); console.log('Updated:', updatedUser); const deletedUser = await service.deleteUser(newUser.id); console.log('Deleted:', deletedUser); await service.onModuleDestroy(); } example();
Always handle errors in real apps to avoid crashes.
Close PrismaClient connection when your app stops to free resources.
Use Prisma migrations to keep your database schema in sync.
Prisma makes database CRUD easy and safe in NestJS.
Use create, findMany, update, and delete methods for CRUD.
Wrap Prisma calls in services for clean code and reuse.
Practice
Solution
Step 1: Understand Prisma CRUD methods
Prisma providescreateto add,findManyto get multiple records,updateto change, anddeleteto remove records.Step 2: Identify method for retrieving multiple records
The methodfindManyis specifically designed to fetch many records from the database.Final Answer:
findMany -> Option CQuick Check:
Retrieve multiple records = findMany [OK]
- Confusing create with findMany
- Using update to retrieve data
- Trying to delete to get records
Solution
Step 1: Identify the method to add a record
Thecreatemethod is used to add new records in Prisma.Step 2: Check the syntax for creating a user
The correct syntax isthis.prisma.user.create({ data: { ... } })wheredataholds the new record's fields.Final Answer:
this.prisma.user.create({ data: { name: 'Alice' } }) -> Option AQuick Check:
Create new record = create method [OK]
- Using findMany instead of create
- Passing data to update without where clause
- Using delete method to add records
this.prisma.user.update({ where: { id: 5 }, data: { email: 'new@example.com' } })What will this operation do?
Solution
Step 1: Understand the update method parameters
Theupdatemethod requires awhereclause to find the record anddatato specify changes.Step 2: Analyze the given call
It targets user withid: 5and changes theemailfield to 'new@example.com'.Final Answer:
Update the email of the user with id 5 to 'new@example.com' -> Option BQuick Check:
Update with where and data changes record [OK]
- Thinking update creates new records
- Confusing update with delete
- Missing where clause causes errors
this.prisma.user.delete({ data: { id: 3 } })Solution
Step 1: Check Prisma delete method syntax
Thedeletemethod requires awhereclause to specify which record to remove.Step 2: Identify the error in the code
The code incorrectly usesdatainstead ofwhere, causing a syntax error.Final Answer:
The delete method should use a where clause, not data -> Option AQuick Check:
Delete needs where, not data [OK]
- Using data instead of where in delete
- Trying to update in delete method
- Omitting where clause causes errors
Solution
Step 1: Understand Prisma's upsert method
Theupsertmethod updates a record if it exists or creates it if not, combining both actions safely.Step 2: Identify correct usage for conditional update or create
Usingupsertwithwhereto find the user,updatefor changes, andcreatefor new record is the best practice.Final Answer:
Use upsert with where, update, and create objects -> Option DQuick Check:
Conditional update or create = upsert [OK]
- Manually catching update errors to create
- Using findMany without update
- Deleting before creating wastes operations
Ready to prove it?
Pass the test and this pattern moves unknown
