Prisma Client helps you talk to your database easily. It lets you get, add, change, or delete data without writing complex SQL.
Prisma Client usage in NestJS
import { PrismaClient } from '@prisma/client'; const prisma = new PrismaClient(); // Example: Get all users async function main() { const users = await prisma.user.findMany(); console.log(users); } main();
PrismaClient is imported from '@prisma/client' and instantiated once.
Use async/await to handle database calls because they return promises.
const allUsers = await prisma.user.findMany();const newUser = await prisma.user.create({ data: { name: 'Anna', email: 'anna@example.com' } });
const updatedUser = await prisma.user.update({ where: { id: 1 }, data: { name: 'Anna Smith' } });
const deletedUser = await prisma.user.delete({ where: { id: 1 } });
This NestJS service uses Prisma Client to connect to the database, add a user, and fetch all users. It connects when the module starts and disconnects when it stops.
import { Injectable, OnModuleInit, OnModuleDestroy } from '@nestjs/common'; import { PrismaClient } from '@prisma/client'; @Injectable() export class UserService implements OnModuleInit, OnModuleDestroy { private prisma = new PrismaClient(); async onModuleInit() { await this.prisma.$connect(); } async onModuleDestroy() { await this.prisma.$disconnect(); } async getAllUsers() { return await this.prisma.user.findMany(); } async createUser(name: string, email: string) { return await this.prisma.user.create({ data: { name, email }, }); } } // Example usage (in some controller or main file): async function main() { const userService = new UserService(); await userService.onModuleInit(); const newUser = await userService.createUser('John Doe', 'john@example.com'); console.log('Created user:', newUser); const users = await userService.getAllUsers(); console.log('All users:', users); await userService.onModuleDestroy(); } main();
Always connect to the database before queries and disconnect after to avoid resource leaks.
Prisma Client methods return promises, so use async/await or .then() to handle results.
Use the Prisma schema file to define your database models before generating Prisma Client.
Prisma Client lets you work with your database using simple JavaScript calls.
Use it in NestJS by importing and creating a PrismaClient instance.
Remember to connect and disconnect Prisma Client properly in your app lifecycle.
Practice
Solution
Step 1: Understand Prisma Client's role
Prisma Client is a tool that helps you talk to your database easily using JavaScript.Step 2: Compare with other options
Handling HTTP requests and routing, managing frontend state, and styling components relate to other parts of an app, not database interaction.Final Answer:
To interact with the database using simple JavaScript calls -> Option AQuick Check:
Prisma Client = database interaction [OK]
- Confusing Prisma Client with HTTP routing
- Thinking Prisma Client manages frontend state
- Assuming Prisma Client styles components
Solution
Step 1: Check the official import syntax
The correct import is from '@prisma/client' and creating a new PrismaClient instance.Step 2: Identify incorrect options
Using require('prisma-client'), importing from 'prisma', or using '@nestjs/prisma' with incorrect instantiation do not match Prisma Client usage.Final Answer:
import { PrismaClient } from '@prisma/client'; const prisma = new PrismaClient(); -> Option AQuick Check:
Correct import and instantiation = import { PrismaClient } from '@prisma/client'; const prisma = new PrismaClient(); [OK]
- Using require instead of import
- Wrong package names like 'prisma-client'
- Confusing NestJS modules with Prisma Client
const user = await prisma.user.findUnique({ where: { id: 5 } });
console.log(user);What will be logged if a user with id 5 exists in the database?
Solution
Step 1: Understand findUnique behavior
findUnique returns a single record matching the condition or null if none found.Step 2: Given user with id 5 exists
The query returns the user object with id 5, so console.log prints that object.Final Answer:
An object containing the user's data with id 5 -> Option DQuick Check:
findUnique with existing id = user object [OK]
- Expecting an array instead of an object
- Assuming null even if user exists
- Thinking it causes syntax error
import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();
async function getUsers() {
const users = prisma.user.findMany();
return users;
}Solution
Step 1: Check async function usage
prisma.user.findMany() returns a Promise, so it must be awaited inside async functions.Step 2: Identify missing await
The code misses 'await' before the call, so it returns a Promise instead of resolved data.Final Answer:
Missing await before prisma.user.findMany() -> Option BQuick Check:
Async DB calls need await [OK]
- Forgetting await on async Prisma calls
- Thinking PrismaClient can't be instantiated
- Assuming findMany() is invalid
Solution
Step 1: Understand PrismaClient lifecycle
PrismaClient should connect once when app starts and disconnect on shutdown to manage resources efficiently.Step 2: Evaluate options
Creating a single PrismaClient instance in a service and using $connect() in onModuleInit() and $disconnect() in onModuleDestroy() leverages NestJS lifecycle hooks properly. Connecting/disconnecting per query, creating new instances per method, or skipping explicit management leads to overhead or resource leaks.Final Answer:
Create PrismaClient instance in a service, call prisma.$connect() in onModuleInit(), and prisma.$disconnect() in onModuleDestroy() -> Option CQuick Check:
Use lifecycle hooks for Prisma connection [OK]
- Creating PrismaClient multiple times
- Connecting/disconnecting on every query
- Ignoring connect/disconnect lifecycle
Ready to prove it?
Pass the test and this pattern moves unknown
