0
0
NestJSframework~30 mins

Migrations in NestJS - Mini Project: Build & Apply

Choose your learning style9 modes available
Database Migrations with NestJS
📖 Scenario: You are building a simple NestJS application that manages a list of books. You need to set up database migrations to create and update the database schema safely over time.
🎯 Goal: Learn how to create and run migrations in a NestJS project using TypeORM to manage database schema changes step-by-step.
📋 What You'll Learn
Create an initial migration file to set up the books table
Add a configuration variable for the migration directory
Write a migration to add a new column to the books table
Run the migration and finalize the setup in the NestJS project
💡 Why This Matters
🌍 Real World
Database migrations help developers safely update database schemas as applications grow and change, avoiding data loss and keeping environments consistent.
💼 Career
Understanding migrations is essential for backend developers working with databases and frameworks like NestJS to maintain and evolve production databases.
Progress0 / 4 steps
1
Create Initial Migration File
Create a migration file named InitialBooksMigration that creates a table called books with columns id (primary key, auto-increment integer) and title (string). Use TypeORM migration syntax inside a class that extends MigrationInterface with up and down methods.
NestJS
Need a hint?

Use queryRunner.createTable inside the up method to create the table. Use queryRunner.dropTable inside the down method to remove it.

2
Add Migration Directory Configuration
In your ormconfig.ts or equivalent TypeORM config file, add a configuration variable called migrationsDir and set it to 'src/migrations'. This will tell TypeORM where to find migration files.
NestJS
Need a hint?

Add migrationsDir: 'src/migrations' inside the exported config object.

3
Add Migration to Add Author Column
Create a new migration class named AddAuthorToBooksMigration that adds a new column called author of type varchar to the books table in the up method. In the down method, remove the author column.
NestJS
Need a hint?

Use queryRunner.addColumn in up and queryRunner.dropColumn in down.

4
Run Migrations and Finalize Setup
In your NestJS main application file or migration script, import DataSource from typeorm, create a new DataSource instance using ormconfig, and call initialize() followed by runMigrations() to apply all pending migrations.
NestJS
Need a hint?

Call initialize() on the DataSource instance, then runMigrations() inside the then callback.