Migration with TypeORM
Explore how to configure, create, run, and revert a TypeORM migration.
We'll cover the following
How to implement a database migration with TypeORM
In this lesson, we’ll explore how to implement a database migration with TypeORM, ensuring that our data model evolves gracefully with the NestJS project.
Migration overview
TypeORM migration allows us to keep the database schema in sync with the changes in the codebase. When we modify a data entity—for example, adding a new field or updating/deleting a field—a migration file can be generated and applied to the database. A data entity refers to a class representing a specific data model that typically corresponds to a table in the database.
One main advantage of migrations is the ability to synchronize the database with the schema defined in the application code and not lose existing data. As the application evolves, the database can adapt gracefully without a complete wipe and recreation. Moreover, the rollback feature provided by the migration tool allows for reverting changes, if needed, giving flexibility and risk mitigation during the development life cycle.
We can track and manage the schema changes over time by storing migration files in a source control system. The integration with source control systems enables the development team to track changes, revert to previous states, and maintain a history of alterations made to the database schema. For example, if issues arise after applying a migration, having migration files in version control enables us to revert to a previous state easily.
The TypeORM migration focuses on managing database schema and doesn’t handle data deletion or restoration directly. To handle data deletion or restoration, we can perform a database backup or create a separate script to delete or restore data. These data scripts can be executed manually as required.
Configure the TypeORM migration tool
To configure the migration tool, we need to set the synchronize
flag to false
in the TypeORM configuration below:
Get hands-on with 1400+ tech skills courses.