Database Management
The project can be in two different states:
- You do not care about migrations yet, because there is no production data yet (or expensive data to seed).
- Or you need to manage migrations.
No migrations needed
Section titled “No migrations needed”Starting fresh
Section titled “Starting fresh”This command will drop the database and re-create it based on your entity files.
pnpm db:freshIf you want also want to seed the database with data, you can use the following command:
pnpm db:fresh:seedSyncing 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.
pnpm db:syncMigrations needed
Section titled “Migrations needed”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.
- Ensure you don’t have any migrations, check the
apps/api/src/modules/db/migrationsfolder. ⚠️ Some are shipped with the boilerplate! - Create the initial migration file
pnpm db:migration:init- 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.
- Set up your infrastructure to run
pnpm db:migrate:upon startup (instead ofpnpm db:syncor other)
And… that’s it! You can deploy this version.
Working with migrations
Section titled “Working with migrations”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.
Creating a new migration
Section titled “Creating a new migration”pnpm db:migrate:createThen, you can run the migration to test it:
pnpm db:migrate:upDeploying a new migration
Section titled “Deploying a new migration”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.