0
0
NestJSframework~5 mins

CRUD with Prisma in NestJS

Choose your learning style9 modes available
Introduction

CRUD means Create, Read, Update, and Delete data. Prisma helps you do these actions easily with your database in a NestJS app.

When you want to add new data to your database.
When you need to get data from your database to show it to users.
When you want to change existing data in your database.
When you want to remove data that is no longer needed.
When building a backend API that talks to a database.
Syntax
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.

Examples
This creates a new user with name and email.
NestJS
await prisma.user.create({ data: { name: 'Alice', email: 'alice@example.com' } });
This gets all users from the database.
NestJS
const users = await prisma.user.findMany();
This updates the user with id 1 to have a new name.
NestJS
await prisma.user.update({ where: { id: 1 }, data: { name: 'Alice Updated' } });
This deletes the user with id 1.
NestJS
await prisma.user.delete({ where: { id: 1 } });
Sample Program

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.

NestJS
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();
OutputSuccess
Important Notes

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.

Summary

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.