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.
#Install the NestJS CLI if you haven't already
npm i -g @nestjs/cli
#Create a new project
nest new my-nest-project
#Navigate into the project directory
cd my-nest-project
#Install TypeORM and a database driver (e.g., PostgreSQL)
npm install @nestjs/typeorm typeorm
Add TypeORM configuration to connect with your database. This is done by importing TypeOrmModule in app.module.ts:
// src/app.module.ts
import { 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 {}
Create a simple entity that represents a database table. For example, we will create a User entity:
// src/user/user.entity.ts
import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm';
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number;
@Column()
name: string;
@Column()
email: string;
}
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 project
npm run build
# Generate a migration based on changes in your entities
npx typeorm migration:generate -n CreateUserTable
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
Here’s how the generated migration file might look:
// src/migration/1357637341275-CreateUserTable.ts
import { 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"`);
}
}
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 YourMigrationName
npm run migration:run
npm run migration:revert
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