Programming Journal

学習したことの整理用です。

NestJS with TypeORM Migrations

OverView

  • NestJS * TypeORM
  • Adding table columns using CLI
  • ts-node and typeorm are already installed

How to

(1. Create an entity)
2. Adding table columns
3. Create a new migration
4. Run migrations

Adding table columns / Edit entity file

import { Entity, Column } from "typeorm";

@Entity()
export class User{

    @Column()
    id: number;

    @Column()
    name: string;

    // Add
    @Column()
    description: string;
}

Create a new migration

"scripts": {
    ...
    "typeorm": "node --require ts-node/register ./node_modules/typeorm/cli.js"
}
npm run typeorm migration:generate -- -n AddDescriptionColumnToUser

it creates migration file

Run migrations

npm run typeorm migration:run

Done 👏

Other Commands

  • Revert migrations npm run typeorm migration:revert

  • Show migrations npm run typeorm migration:show

  • Drop database schema ※ To dompletely drop a database schema ☠️ npm run typeorm schema:drop

Links

Using CLI - typeorm

TypeORM - Amazing ORM for TypeScript and JavaScript (ES7, ES6, ES5). Supports MySQL, PostgreSQL, MariaDB, SQLite, MS SQL Server, Oracle, WebSQL databases. Works in NodeJS, Browser, Ionic, Cordova and Electron platforms.