Skip to content

Database Management

The project can be in two different states:

  1. You do not care about migrations yet, because there is no production data yet (or expensive data to seed).
  2. Or you need to manage migrations.

This command will drop the database and re-create it based on your entity files.

Terminal window
pnpm db:fresh

If you want also want to seed the database with data, you can use the following command:

Terminal window
pnpm db:fresh:seed

Syncing changes without dropping the database

Section titled “Syncing changes without dropping the database”

This command will sync the changes to the database based on your entity files. Note that this can lead to some errors.

Terminal window
pnpm db:sync

The switch to production: setting up migrations

Section titled “The switch to production: setting up migrations”

You were happily using sync, but it’s time to launch the project and you need to setup migrations.

  1. Ensure you don’t have any migrations, check the apps/api/src/modules/db/migrations folder. ⚠️ Some are shipped with the boilerplate!
  2. Create the initial migration file
Terminal window
pnpm db:migration:init
  1. Clean your production database: MikroORM will need an empty database to apply the initial migration. You may also want to do that for you pre-production environment.
  2. Set up your infrastructure to run pnpm db:migrate:up on startup (instead of pnpm db:sync or other)

And… that’s it! You can deploy this version.

When you make any changes to your entities, you need to create a new migration file.

With other ORMs, you would need to reset your database to the previous state, but MikroORM uses the snapshot file to track the state of the database, so no need to checkout main.

Terminal window
pnpm db:migrate:create

Then, you can run the migration to test it:

Terminal window
pnpm db:migrate:up

Migrations are tricky because they order of execution matters. If another developer made some changes to the database, remember to pull their changes and apply their migrations first.

When several PRs are opened and are making changes to the database, it’s a good practise to synchronize between developers to ensure migrations are runned in a correct order.

When you are ready to deploy your changes, just push your changes and your container / launch command should run the migrations via pnpm db:migrate:up.

Remember to respect the production safety rules described in the Database Migrations page.