Database migrations are a way of propagating changes you make to your entities into your database schema. The changes you make to your models (adding a field, deleting an entity, etc.) do not automatically modify your database. You have to do it yourself.
You have two options: update the database schema manually (using database software, for example) or run migrations.
Migrations are a programmatic technique for updating or reverting a database schema in a predictable and repeatable way. They are defined with classes, each of which has an
up method and a
down method. The first one contains SQL queries to update the database schema to reflect the new models. The second contains SQL queries to revert the changes made by the
Theses classes are located in separate files in the
Example of a migration file
Usually, you do not need to write migrations manually. TypeORM offers a powerful feature to generate your migration files based on the changes you make to your entities.
1. Create a new
2. Build the application.
3. Generate a migration file.
A new file
xxx-add-user.ts appears in
4. Build and run the migration.
5. Add new columns to the entity.
6. Build the application.
7. Generate another migration file.
xxx-add-email-and-password.ts appears in
8. Build and run the migration.
These two options are particularly useful for testing.
synchronize- Indicates if database schema should be auto created on every application launch.
dropSchema- Drops the schema each time connection is being established.
synchronize option for production is not recommended as you could loose data by mistake.
The TypeORM documentation gives more details on how to write migrations.