📖 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
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
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
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
Hint
Use new PrismaClient() to access your database and return all books with findMany().
Practice
(1/5)
1. What is the main purpose of Prisma migrations in a NestJS project?
easy
A. To optimize API response times
B. To generate frontend UI components automatically
C. To manage user authentication and sessions
D. To keep the database schema in sync with the application code
Solution
Step 1: Understand Prisma migrations role
Prisma migrations help update the database schema to match changes in your code models.
Step 2: Compare options
Options A, B, and C relate to performance, UI, and authentication, which are unrelated to migrations.
Final Answer:
To keep the database schema in sync with the application code -> Option D
Quick Check:
Prisma migrations = sync DB schema [OK]
Hint: Migrations sync DB schema with code changes [OK]
Common Mistakes:
Confusing migrations with frontend code generation
Thinking migrations handle user sessions
Assuming migrations optimize API speed
2. Which command correctly creates a new migration during development with Prisma in NestJS?
easy
A. npx prisma migrate dev --name addUserTable
B. npx prisma migrate deploy --name addUserTable
C. npx prisma generate --name addUserTable
D. npx prisma migrate reset --name addUserTable
Solution
Step 1: Identify the correct command for creating migrations
The command npx prisma migrate dev --name is used to create and apply migrations during development.
Step 2: Eliminate incorrect commands
migrate deploy applies migrations in production, generate creates Prisma client code, and migrate reset resets the database.
Final Answer:
npx prisma migrate dev --name addUserTable -> Option A
Quick Check:
Dev migrations use migrate dev [OK]
Hint: Use migrate dev to create migrations in development [OK]
Common Mistakes:
Using migrate deploy instead of migrate dev for new migrations
Confusing generate with migration commands
Trying to reset DB when creating migrations
3. Given the following Prisma schema change and migration command, what will happen?
model User {
id Int @id @default(autoincrement())
email String @unique
name String?
}
// Command run:
npx prisma migrate dev --name addNameField
medium
A. The database schema remains unchanged
B. An error occurs because 'name' field is optional
C. A migration file is created adding the optional 'name' field to User table
D. The User table is deleted and recreated
Solution
Step 1: Analyze schema change
The schema adds an optional 'name' field to the User model, which is a valid change.
Step 2: Understand migrate dev behavior
Running npx prisma migrate dev --name addNameField creates a migration file reflecting this change and applies it to the database.
Final Answer:
A migration file is created adding the optional 'name' field to User table -> Option C
Quick Check:
Optional field added = migration created [OK]
Hint: Optional fields create migrations without errors [OK]
Common Mistakes:
Thinking optional fields cause errors
Assuming schema stays unchanged without manual DB update
Believing migrate dev deletes tables
4. You run npx prisma migrate deploy in production but get an error saying migrations are missing. What is the likely cause?
medium
A. You forgot to create migration files locally before deploying
B. The database connection string is incorrect
C. You ran migrate dev instead of migrate deploy
D. Prisma client was not generated
Solution
Step 1: Understand migrate deploy requirements
migrate deploy applies existing migration files to production; it does not create them.
Step 2: Identify cause of missing migrations error
If migration files were not created locally (e.g., with migrate dev), deploy will fail due to missing files.
Final Answer:
You forgot to create migration files locally before deploying -> Option A
Quick Check:
Deploy needs existing migrations [OK]
Hint: Create migrations locally before deploying to production [OK]
Common Mistakes:
Confusing migrate dev and migrate deploy roles
Ignoring missing migration files
Assuming wrong DB connection causes missing migrations error
5. You want to add a new required field age Int to your User model in Prisma. However, your database already has existing users without this field. What is the best way to handle this migration safely?
hard
A. Delete all existing users before running migration
B. Add the field as optional first, run a migration, then update data and make it required in a second migration
C. Add the required field directly and run migrate dev once
D. Skip migrations and manually update the database schema
Solution
Step 1: Understand required field impact
Adding a required field means existing rows must have a value, or migration will fail.
Step 2: Apply a two-step migration strategy
First add the field as optional, migrate, update existing data with values, then change field to required and migrate again.
Final Answer:
Add the field as optional first, run a migration, then update data and make it required in a second migration -> Option B
Quick Check:
Two-step migration avoids missing data errors [OK]
Hint: Add required fields in two steps to avoid errors [OK]