TypeORM's Migration is an important tool for managing database schema changes:
-
Create migration:
bashtypeorm migration:generate -n MigrationName -
Run migration:
bashtypeorm migration:run -
Rollback migration:
bashtypeorm migration:revert -
Migration file structure:
- up(): Execute migration, create or modify table structure
- down(): Rollback migration, undo the operations of up()
-
Using in code:
typescriptawait 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.