DEV Community

Cover image for Configure TypeORM migrations in 5 minutes
Andreas Bergström
Andreas Bergström

Posted on • Edited on • Originally published at andreasbergstrom.dev

Configure TypeORM migrations in 5 minutes

Setting up TypeORM migrations in a NestJS project is fiddly across two configs and four npm scripts the first time you do it, but mechanical once you know the shape. Wire migrationsRun: true into TypeOrmModule.forRootAsync, add a separate typeorm.config.ts DataSource for the CLI to import, and four package.json scripts cover run/generate/create/revert.

The full post has the exact app.module.ts, typeorm.config.ts, and package.json snippets to copy, plus notes on why synchronize should never be true in production and how generate-migration diffs your entities against the live schema to write the SQL for you.


Originally published at andreasbergstrom.dev — read the full post there.

Top comments (1)

Collapse
 
osalumense profile image
Stephen Akugbe • Edited

This is a very straightforward guide. I stumbled upon this when trying to set up TypeORM migrations on a new project, and it works perfectly. Thanks so much for this, Andreas.

Just to add, in case you're working with TS and also using individual connection strings in place of a DB URL, update your typeorm.config.ts file to this:

import { DataSource } from 'typeorm';
import { ConfigService } from '@nestjs/config';
import { config } from 'dotenv';

config();

const configService = new ConfigService();

export default new DataSource({
  type: 'postgres',
  host: configService.get<string>('DB_HOST'),
  port: configService.get<number>('DB_PORT'),
  username: configService.get<string>('DB_USERNAME'),
  password: configService.get<string>('DB_PASSWORD'),
  database: configService.get<string>('DB_NAME'),
  entities: ['dist/**/*.entity{.ts,.ts}'],
  migrations: ['src/migrations/*.ts'],
});
Enter fullscreen mode Exit fullscreen mode