Nest.js migrations in TypeORM

Nest.js migrations in TypeORM

I see that from time to time developers who are new to the NestJS and are using TypeORM are having a problems with creating a database migrations.
Let’s clear one thing right away. The TypeORM command line tool currently is not compatible with a NestJS and you can’t generate migrations out of the box using cli.

You have to create a file manually. Append JavaScript timestamp to it. And save the file into the migrations folder you’re defined in your configuration.

File must implement MigrationInterface in the
up(queryRunner: QueryRunner): Promise<any>
method you define the your entities / tables properties and how they are created like this:

public async up(queryRunner: QueryRunner): Promise</any/> {
  await queryRunner.createTable(new Table({
    name: 'languages',
    columns: [
      {
        name: 'id',
        type: 'int',
        isPrimary: true,
      },
      {
        name: 'code',
        type: 'varchar',
      },
      {
        name: 'created_at',
        type: 'datetime',
      },
      {
        name: 'updated_at',
        type: 'datetime',
      },
    ],
  }), true);
}

In the down(queryRunner: QueryRunner): Promise<any> you implement the tear down method. Meaning how to undo what you created in the first one.

Example:

public async down(queryRunner: QueryRunner): Promise<any> {
  await queryRunner.dropTable('languages');
}

I hope that helps.

If you are in the development process what you can do to avoid writing migration as soon as you start developing an app is set option in databaseConnectionOptions SYNCHRONIZE:true and it will synchronize your entities with a database columns each time you change them.

But make sure you turn synchronise option is  off when you launch the application in production. To make database changes use migrations setting in options set to true.

Have a nice day!

Show Comments