Bird
Raised Fist0
NestJSframework~5 mins

CRUD with Prisma in NestJS

Choose your learning style10 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.

Practice

(1/5)
1. In NestJS with Prisma, which method is used to retrieve multiple records from the database?
easy
A. create
B. update
C. findMany
D. delete

Solution

  1. Step 1: Understand Prisma CRUD methods

    Prisma provides create to add, findMany to get multiple records, update to change, and delete to remove records.
  2. Step 2: Identify method for retrieving multiple records

    The method findMany is specifically designed to fetch many records from the database.
  3. Final Answer:

    findMany -> Option C
  4. Quick Check:

    Retrieve multiple records = findMany [OK]
Hint: Remember: findMany fetches many records [OK]
Common Mistakes:
  • Confusing create with findMany
  • Using update to retrieve data
  • Trying to delete to get records
2. Which of the following is the correct syntax to create a new user record using Prisma in a NestJS service?
easy
A. this.prisma.user.create({ data: { name: 'Alice' } })
B. this.prisma.user.findMany({ data: { name: 'Alice' } })
C. this.prisma.user.update({ data: { name: 'Alice' } })
D. this.prisma.user.delete({ data: { name: 'Alice' } })

Solution

  1. Step 1: Identify the method to add a record

    The create method is used to add new records in Prisma.
  2. Step 2: Check the syntax for creating a user

    The correct syntax is this.prisma.user.create({ data: { ... } }) where data holds the new record's fields.
  3. Final Answer:

    this.prisma.user.create({ data: { name: 'Alice' } }) -> Option A
  4. Quick Check:

    Create new record = create method [OK]
Hint: Use create with data object to add records [OK]
Common Mistakes:
  • Using findMany instead of create
  • Passing data to update without where clause
  • Using delete method to add records
3. Given this Prisma update call in a NestJS service:
this.prisma.user.update({ where: { id: 5 }, data: { email: 'new@example.com' } })

What will this operation do?
medium
A. Delete the user with id 5
B. Update the email of the user with id 5 to 'new@example.com'
C. Create a new user with id 5 and email 'new@example.com'
D. Return all users with email 'new@example.com'

Solution

  1. Step 1: Understand the update method parameters

    The update method requires a where clause to find the record and data to specify changes.
  2. Step 2: Analyze the given call

    It targets user with id: 5 and changes the email field to 'new@example.com'.
  3. Final Answer:

    Update the email of the user with id 5 to 'new@example.com' -> Option B
  4. Quick Check:

    Update with where and data changes record [OK]
Hint: Update needs where to find record, data to change [OK]
Common Mistakes:
  • Thinking update creates new records
  • Confusing update with delete
  • Missing where clause causes errors
4. What is wrong with this Prisma delete call in a NestJS service?
this.prisma.user.delete({ data: { id: 3 } })
medium
A. The delete method should use a where clause, not data
B. The delete method cannot delete by id
C. The syntax is correct and will delete user with id 3
D. The delete method requires an update object

Solution

  1. Step 1: Check Prisma delete method syntax

    The delete method requires a where clause to specify which record to remove.
  2. Step 2: Identify the error in the code

    The code incorrectly uses data instead of where, causing a syntax error.
  3. Final Answer:

    The delete method should use a where clause, not data -> Option A
  4. Quick Check:

    Delete needs where, not data [OK]
Hint: Delete uses where to find record, not data [OK]
Common Mistakes:
  • Using data instead of where in delete
  • Trying to update in delete method
  • Omitting where clause causes errors
5. You want to update a user's name only if the user exists, otherwise create a new user with that name using Prisma in NestJS. Which approach correctly handles this logic?
hard
A. Use delete then create to replace the user
B. Call update and if it fails, call create manually
C. Use findMany then create without update
D. Use upsert with where, update, and create objects

Solution

  1. Step 1: Understand Prisma's upsert method

    The upsert method updates a record if it exists or creates it if not, combining both actions safely.
  2. Step 2: Identify correct usage for conditional update or create

    Using upsert with where to find the user, update for changes, and create for new record is the best practice.
  3. Final Answer:

    Use upsert with where, update, and create objects -> Option D
  4. Quick Check:

    Conditional update or create = upsert [OK]
Hint: Use upsert to update or create in one call [OK]
Common Mistakes:
  • Manually catching update errors to create
  • Using findMany without update
  • Deleting before creating wastes operations
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard