0
0
NestJSframework~5 mins

Migrations in NestJS

Choose your learning style9 modes available
Introduction

Migrations help you change your database step-by-step safely. They keep track of what changes were made so your data stays organized.

When you add a new table to your database.
When you change a column type or name.
When you remove a column or table.
When you want to share database changes with your team.
When you deploy updates to your app's database.
Syntax
NestJS
npx typeorm migration:create -n MigrationName

// Then edit the generated migration file:
export class MigrationName implements MigrationInterface {
  public async up(queryRunner: QueryRunner): Promise<void> {
    // code to apply changes
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    // code to undo changes
  }
}

Use up to add or change database structure.

Use down to undo those changes if needed.

Examples
This command creates a new migration file named AddUsersTable.
NestJS
npx typeorm migration:create -n AddUsersTable
This migration adds a users table in up and removes it in down.
NestJS
export class AddUsersTable implements MigrationInterface {
  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`CREATE TABLE users (id INT PRIMARY KEY, name VARCHAR(100))`);
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`DROP TABLE users`);
  }
}
This command runs all pending migrations to update the database.
NestJS
npx typeorm migration:run
This command reverts the last run migration to undo changes.
NestJS
npx typeorm migration:revert
Sample Program

This migration creates a products table with id, name, and price columns. Running up adds the table. Running down removes it.

NestJS
import { MigrationInterface, QueryRunner } from 'typeorm';

export class AddProductsTable1680000000000 implements MigrationInterface {
  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`
      CREATE TABLE products (
        id INT PRIMARY KEY AUTO_INCREMENT,
        name VARCHAR(255) NOT NULL,
        price DECIMAL(10,2) NOT NULL
      )
    `);
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`DROP TABLE products`);
  }
}

// To run this migration, use:
// npx typeorm migration:run

// To revert it, use:
// npx typeorm migration:revert
OutputSuccess
Important Notes

Always write the down method to safely undo changes.

Run migrations in your development and production environments to keep databases in sync.

Use descriptive names for migrations to remember what each one does.

Summary

Migrations help you change your database step-by-step.

Use up to apply changes and down to undo them.

Run migrations with commands like migration:run and migration:revert.