NodeJS

NodeJS With Typeorm Migration


What is Migration in Node.js?

Migration in Node.js talk, especially concerning databases is the management and application of incremental changes to your database structure. It could mean creating, altering or deleting tables, columns or records and changing relationships between data entities. This allows you to version and evolve your database schema with your application code, ensuring consistency and traceability as your project grows.

1. Setting Up a NestJS Project with TypeORM

#Install the NestJS CLI if you haven't alreadynpm i -g @nestjs/cli #Create a new project nest new my-nest-project #Navigate into the project directorycd my-nest-project #Install TypeORM and a database driver (e.g., PostgreSQL) npm install @nestjs/typeorm typeorm   

2. Configure TypeORM in - app.module.ts

Add TypeORM configuration to connect with your database. This is done by importing   TypeOrmModule in app.module.ts:

// src/app.module.tsimport { Module } from '@nestjs/common';import { TypeOrmModule } from '@nestjs/typeorm';import { User } from './user/user.entity'; // Example entity@Module({  imports: [    TypeOrmModule.forRoot({      type: 'postgres', // You can change this based on your database      host: 'localhost',      port: 5432,      username: 'yourusername',      password: 'yourpassword',      database: 'yourdatabase',      entities: [User],      synchronize: false, // Disable in production to avoid data loss      migrations: ['dist/migration/*.js'],      cli: {        migrationsDir: 'src/migration',      },    }),  ],})export class AppModule {}

 

3. Create an Entity

Create a simple entity that represents a database table. For example, we will create a User entity:

// src/user/user.entity.tsimport { Entity, PrimaryGeneratedColumn, Column } from 'typeorm';@Entity()export class User {  @PrimaryGeneratedColumn()  id: number;   @Column()  name: string;   @Column()  email: string;}

 

4. Generate a Migration

To generate a migration, you can use the TypeORM CLI. First, make sure to build the project so that the generated JavaScript files are available:

# Compile the projectnpm run build # Generate a migration based on changes in your entitiesnpx typeorm migration:generate -n CreateUserTable  

5. Running Migrations

To apply migrations to the database, run:

npx typeorm migration:run 

This command executes the up method of all pending migrations. If you need to roll back a migration, you can use:

npx typeorm migration:revert  

6. Example Migration File

Here’s how the generated migration file might look:

// src/migration/1357637341275-CreateUserTable.tsimport { MigrationInterface, QueryRunner } from 'typeorm'; export class CreateUserTable1357637341275 implements MigrationInterface {  public async up(queryRunner: QueryRunner): Promise<void> {    await queryRunner.query(`      CREATE TABLE "user" (        "id" SERIAL NOT NULL,        "name" character varying NOT NULL,        "email" character varying NOT NULL,        PRIMARY KEY ("id")      )    `);  }  public async down(queryRunner: QueryRunner): Promise<void> {    await queryRunner.query(`DROP TABLE "user"`);  }}  

7. Running Migrations in a NestJS Environment

To use the typeorm CLI commands conveniently with NestJS, you can add some helpful scripts in your package.json file:

"scripts": {  "typeorm": "ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli.js",  "migration:generate": "npm run build && npm run typeorm migration:generate -n",  "migration:run": "npm run typeorm migration:run",  "migration:revert": "npm run typeorm migration:revert"} 

Now you can generate, run, and revert migrations using: 

npm run migration:generate -- -n YourMigrationNamenpm run migration:runnpm run migration:revert  

Best Practices

Disable Synchronize in Production: If you set the option synchronize: true inside of TypeORM, any change in schema will automatically impact changes in the database. however, in production environments it may lead to data loss, so prefer migrations for the schema changes safely.

Manage Rollbacks:Don't ever let rollbacks break things.

Testing the Migrations in a Staging Environment: You always want to test your migrations before you put them into production.

Ready to transform your business with our technology solutions?   Contact Us today to Leverage Our NodeJS Expertise.

0

NodeJS

Related Center Of Excellence