Prisma helps you talk to your database easily. Setting it up in NestJS lets your app save and get data simply and safely.
Prisma setup in NestJS
1. Install Prisma and its dependencies: npm install @prisma/client npm install -D prisma 2. Initialize Prisma: npx prisma init 3. Define your database schema in prisma/schema.prisma 4. Generate Prisma Client: npx prisma generate 5. Create a PrismaService in NestJS to use Prisma Client: import { Injectable, OnModuleInit, OnModuleDestroy } from '@nestjs/common'; import { PrismaClient } from '@prisma/client'; @Injectable() export class PrismaService extends PrismaClient implements OnModuleInit, OnModuleDestroy { async onModuleInit() { await this.$connect(); } async onModuleDestroy() { await this.$disconnect(); } } 6. Provide PrismaService in your module and inject it where needed.
Prisma Client is auto-generated code to talk to your database.
PrismaService manages database connection lifecycle in NestJS.
prisma/schema.prisma
model User {
id Int @id @default(autoincrement())
name String
email String @unique
}import { Injectable } from '@nestjs/common'; import { PrismaClient } from '@prisma/client'; @Injectable() export class PrismaService extends PrismaClient { constructor() { super(); } }
import { Module } from '@nestjs/common'; import { PrismaService } from './prisma.service'; @Module({ providers: [PrismaService], exports: [PrismaService], }) export class PrismaModule {}
This example shows how to set up PrismaService with lifecycle hooks, create a UserService to add and get users, and provide them in a NestJS module.
import { Module, Injectable, OnModuleInit, OnModuleDestroy } from '@nestjs/common'; import { PrismaClient } from '@prisma/client'; @Injectable() export class PrismaService extends PrismaClient implements OnModuleInit, OnModuleDestroy { async onModuleInit() { await this.$connect(); } async onModuleDestroy() { await this.$disconnect(); } } @Injectable() export class UserService { constructor(private prisma: PrismaService) {} async createUser(name: string, email: string) { return this.prisma.user.create({ data: { name, email } }); } async getUsers() { return this.prisma.user.findMany(); } } @Module({ providers: [PrismaService, UserService], exports: [UserService], }) export class AppModule {}
Always run npx prisma generate after changing your schema.
Use lifecycle hooks in PrismaService to manage database connections cleanly.
Inject PrismaService in your services to access the database safely.
Prisma setup in NestJS connects your app to a database with easy and safe code.
Define your database schema, generate Prisma Client, and create a PrismaService.
Use PrismaService in your NestJS services to read and write data.
Practice
PrismaService in a NestJS application?Solution
Step 1: Understand PrismaService role
PrismaService wraps the Prisma Client to provide a single database connection instance across the app.Step 2: Differentiate from other roles
It does not handle HTTP or define schema; those are handled by controllers and Prisma schema files respectively.Final Answer:
To provide a reusable database client instance for querying the database -> Option AQuick Check:
PrismaService = database client provider [OK]
- Confusing PrismaService with controllers
- Thinking PrismaService defines schema
- Assuming PrismaService manages config
Solution
Step 1: Check import source
PrismaService is a custom service, so it must be imported from its local file, not from '@nestjs/common' or external packages.Step 2: Verify module metadata
It should be listed under providers and exports to be injectable and reusable in other modules.Final Answer:
import { PrismaService } from './prisma.service'; @Module({ providers: [PrismaService], exports: [PrismaService] }) -> Option BQuick Check:
Local import + providers and exports = correct setup [OK]
- Importing PrismaService from wrong package
- Adding PrismaService to controllers instead of providers
- Using imports array instead of providers
console.log(user) output if the user with ID 1 exists?
async getUserById(id: number) {
return this.prisma.user.findUnique({ where: { id } });
}
const user = await prismaService.getUserById(1);
console.log(user);Solution
Step 1: Understand findUnique behavior
findUnique returns a single record matching the unique filter or null if none found.Step 2: Given user with ID 1 exists
The method returns the user object with ID 1, so console.log prints that object.Final Answer:
An object containing the user's data with ID 1 -> Option CQuick Check:
findUnique returns single object or null [OK]
- Thinking findUnique returns an array
- Assuming it always returns null
- Confusing findUnique with findMany
Cannot read property 'user' of undefined. What is the likely cause?
async getAllUsers() {
return this.prisma.user.findMany();
}
Options:Solution
Step 1: Analyze error message
'Cannot read property user of undefined' meansthis.prismais undefined in the service.Step 2: Check PrismaService initialization
Prisma Client must be instantiated and assigned tothis.prismain the constructor; missing this causes the error.Final Answer:
The Prisma Client instance was not initialized in PrismaService -> Option AQuick Check:
Uninitialized prisma client = undefined error [OK]
- Forgetting to instantiate PrismaClient in PrismaService
- Assuming findMany needs parameters
- Thinking method must be static
Solution
Step 1: Understand fetching related data
To get posts with their authors, usefindManywithinclude: { author: true }to load related author data.Step 2: Check other options
return this.prisma.post.findMany({ select: { authorId: true } }); only selects authorId, not author object. return this.prisma.post.findUnique({ where: { id: 1 }, include: { author: true } }); fetches one post, not all. return this.prisma.post.findMany({ where: { author: true } }); uses invalid where clause.Final Answer:
return this.prisma.post.findMany({ include: { author: true } }); -> Option DQuick Check:
Include loads related models in findMany [OK]
- Using select instead of include for relations
- Using findUnique when multiple records needed
- Incorrect where clause for relations
Ready to prove it?
Pass the test and this pattern moves unknown
