How to configure TypeOrm and migrations in NestJs? – Nestjs

by
Ali Hasan
database-migration nestjs node.js typeorm

Quick Fix: In NestJS, you can easily set up TypeORM and migrations. Firstly, configure your ormconfig.ts to define your database connection and specify the path to your entities and migrations. Next, import the dataSource into your main AppModule and use the TypeOrmModule.forRoot() method to register it. Lastly, add the necessary scripts to your package.json for generating and running migrations. By following these steps, you can effectively manage your database interactions in your NestJS application.

The Solutions:

Solution 1: Configuring TypeOrm and Migrations in NestJs

  1. Create a Data Source: Store the ORM configuration in a separate file (ormconfig.ts) and create a data source using it. This file should contain the database connection details, entities, and migration settings.

  2. Import the Data Source: Import the created data source into your application module (AppModule).

  3. Add Migration Scripts: Add scripts to your package.json to generate, run, and revert migrations.

  4. Create a Shell File: Create a shell file (app-env.sh) to set the necessary environment variables for the migrations.

  5. Generate Migrations: Use the npm run migration:generate command to generate migrations.

  6. Run Migrations: Execute npm run migration:run to apply the migrations to the database.

  7. Revert Migrations (Optional): If needed, run npm run migration:revert to undo the applied migrations.

Q&A

How can I configure TypeOrm and migrations in NestJS?

Create a data source using orm config and import it in your app.

How to generate migrations in NestJS?

Use the typeorm command with the migration:generate flag.

How can I run migrations in NestJS?

Use the typeorm command with the migration:run flag.

Video Explanation:

The following video, titled "NestJs migrations with TypeORM 0.3 (latest) - How to set it up from ...", provides additional insights and in-depth exploration related to the topics discussed in this post.

Play video

Nest JS allows you to maintain migrations for every database level changes that you want to perform. The latest version of TypeORM i.e. 0.3x ...