Bird
Raised Fist0
NestJSframework~10 mins

Prisma migrations in NestJS - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Prisma migrations
Write schema.prisma
↓
Run prisma migrate dev
↓
Migration files created
↓
Database schema updated
↓
Application uses updated schema
↓
Repeat for new changes
This flow shows how you write your Prisma schema, run migrations to update the database, and then use the updated schema in your NestJS app.
Execution Sample
NestJS
model User {
  id    Int    @id @default(autoincrement())
  email String @unique
  name  String?
}

// Run: npx prisma migrate dev --name init
Defines a User model and runs a migration to create the corresponding database table.
Execution Table
StepActionInput/CommandEffectOutput/Result
1Write schemaAdd User model to schema.prismaSchema file updatedUser model defined
2Run migrationnpx prisma migrate dev --name initMigration process startsMigration files created
3Apply migrationDatabase updatedDatabase schema matches User modelUser table created
4Generate clientPrisma client updatedClient reflects new schemaClient ready to use
5Use in appNestJS uses Prisma clientApp can query User tableData operations succeed
6ExitNo more migrationsProcess endsDatabase and app in sync
💡 No more schema changes, migration process complete
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3After Step 4Final
schema.prismaempty or old schemaUser model addedUser model unchangedUser model unchangedUser model unchangedUser model defined
migration filesnonenoneinit migration createdinit migration appliedinit migration appliedinit migration applied
database schemaold or emptyold or emptyold or emptyUser table createdUser table createdUser table created
Prisma clientold versionold versionold versionupdated with User modelupdated with User modelupdated with User model
Key Moments - 2 Insights
Why do we need to run 'prisma migrate dev' after changing schema.prisma?
Because the migration command creates files and updates the database schema to match your Prisma schema. Without it, the database won't reflect your changes (see execution_table step 2 and 3).
What happens if you change schema.prisma but don't generate the Prisma client?
Your app will use an outdated client that doesn't know about new models or fields. Step 4 in the execution_table shows client generation is needed to keep the client in sync.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is created at step 2?
ADatabase tables
BMigration files
CPrisma client
DNestJS modules
💡 Hint
Check the 'Effect' and 'Output/Result' columns in step 2 of the execution_table.
At which step does the database schema get updated?
AStep 3
BStep 1
CStep 4
DStep 5
💡 Hint
Look for 'Database schema matches User model' in the 'Effect' column.
If you skip step 4, what problem will you face?
AMigration files won't be created
BDatabase schema won't update
CPrisma client won't reflect schema changes
DNestJS app won't start
💡 Hint
Refer to the 'Prisma client' variable in variable_tracker after step 4.
Concept Snapshot
Prisma migrations let you update your database schema safely.
1. Edit schema.prisma to define models.
2. Run 'npx prisma migrate dev --name <desc>' to create migration files and update DB.
3. Prisma client regenerates to match schema.
4. Use updated client in NestJS app.
Repeat for every schema change.
Full Transcript
Prisma migrations in NestJS start by writing or updating the schema.prisma file to define your data models. Then, you run the command 'npx prisma migrate dev --name <migration_name>' which creates migration files and applies changes to your database schema. After the database updates, Prisma regenerates its client to reflect the new schema. Finally, your NestJS application uses this updated client to interact with the database. This process repeats whenever you change your data models, ensuring your database and app stay in sync.

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

  1. Step 1: Understand Prisma migrations role

    Prisma migrations help update the database schema to match changes in your code models.
  2. Step 2: Compare options

    Options A, B, and C relate to performance, UI, and authentication, which are unrelated to migrations.
  3. Final Answer:

    To keep the database schema in sync with the application code -> Option D
  4. 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

  1. 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.
  2. Step 2: Eliminate incorrect commands

    migrate deploy applies migrations in production, generate creates Prisma client code, and migrate reset resets the database.
  3. Final Answer:

    npx prisma migrate dev --name addUserTable -> Option A
  4. 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

  1. Step 1: Analyze schema change

    The schema adds an optional 'name' field to the User model, which is a valid change.
  2. 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.
  3. Final Answer:

    A migration file is created adding the optional 'name' field to User table -> Option C
  4. 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

  1. Step 1: Understand migrate deploy requirements

    migrate deploy applies existing migration files to production; it does not create them.
  2. 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.
  3. Final Answer:

    You forgot to create migration files locally before deploying -> Option A
  4. 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

  1. Step 1: Understand required field impact

    Adding a required field means existing rows must have a value, or migration will fail.
  2. 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.
  3. Final Answer:

    Add the field as optional first, run a migration, then update data and make it required in a second migration -> Option B
  4. Quick Check:

    Two-step migration avoids missing data errors [OK]
Hint: Add required fields in two steps to avoid errors [OK]
Common Mistakes:
  • Adding required fields directly causing migration failure
  • Deleting data unnecessarily
  • Skipping migrations and editing DB manually
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