0
0
NestJSframework~30 mins

Prisma migrations in NestJS - Mini Project: Build & Apply

Choose your learning style9 modes available
Prisma Migrations with NestJS
📖 Scenario: You are building a simple NestJS backend application that manages a list of books. You want to use Prisma ORM to handle your database schema and migrations.This project will guide you through setting up Prisma migrations step-by-step to create and update your database schema safely.
🎯 Goal: By the end, you will have a Prisma schema file defining a Book model, a migration created and applied to your database, and a NestJS service ready to use Prisma Client to access the Book table.
📋 What You'll Learn
Create a Prisma schema file with a Book model
Configure the database connection URL
Generate and apply a Prisma migration
Use Prisma Client in a NestJS service to query books
💡 Why This Matters
🌍 Real World
Prisma migrations help developers safely evolve their database schema as application requirements change, avoiding manual database edits.
💼 Career
Understanding Prisma migrations and integrating Prisma Client in NestJS is valuable for backend developers working with modern Node.js frameworks and relational databases.
Progress0 / 4 steps
1
Create Prisma schema with Book model
Create a file named schema.prisma with a datasource block for PostgreSQL using the URL postgresql://user:password@localhost:5432/mydb. Then add a generator block for Prisma Client. Finally, define a model Book with fields: id Int @id @default(autoincrement()), title String, and author String.
NestJS
Need a hint?

Remember to define datasource and generator blocks before the model.

2
Configure environment variable for database URL
Create a file named .env in your project root. Add a line setting DATABASE_URL="postgresql://user:password@localhost:5432/mydb". Then update schema.prisma to use env("DATABASE_URL") for the url in the datasource block.
NestJS
Need a hint?

Use env("DATABASE_URL") in schema.prisma and set the exact DATABASE_URL in .env.

3
Generate and apply Prisma migration
Run the command npx prisma migrate dev --name init in your terminal to create and apply the initial migration based on your schema.
NestJS
Need a hint?

This command creates a migration folder and updates your database schema.

4
Use Prisma Client in NestJS service
In your NestJS service file, import PrismaClient from @prisma/client. Create a class BooksService with a private prisma property initialized as new PrismaClient(). Add an async method getAllBooks() that returns this.prisma.book.findMany().
NestJS
Need a hint?

Use new PrismaClient() to access your database and return all books with findMany().