乐闻世界logo
搜索文章和话题

How to use migrations in TypeORM?

2月17日 22:43

TypeORM's Migration is an important tool for managing database schema changes:

  1. Create migration:

    bash
    typeorm migration:generate -n MigrationName
  2. Run migration:

    bash
    typeorm migration:run
  3. Rollback migration:

    bash
    typeorm migration:revert
  4. Migration file structure:

    • up(): Execute migration, create or modify table structure
    • down(): Rollback migration, undo the operations of up()
  5. Using in code:

    typescript
    await dataSource.runMigrations(); await dataSource.undoLastMigration();

Advantages of migrations include:

  • Version control database structure
  • Keep database synchronized during team collaboration
  • Can rollback to previous versions
  • Support safe deployment in production environments

It's recommended to generate migration files after each entity modification during development, and test migration and rollback operations before deployment.

标签:TypeORM