Database Migrations with TypeORM in NestJS
Syed Ali Hamza Zaidi ?
Software Engineer | MERN | Web 3.0 | Nest JS | Next JS | React JS | Node JS | Postgres | MySQL | MongoDB | JavaScript | TypeScript | Material UI | Bootstrap 5 | Tailwind | CSS-3 | HTML-5
Introduction:
NestJS, a popular TypeScript framework for building server-side applications, often integrates with Object-Relational Mapping (ORM) libraries like TypeORM to handle database operations. One critical aspect of database management is handling schema changes over time, and this is where database migrations come into play. In this article, we'll explore the process of using TypeORM for database migrations in a NestJS application.
Installation:
Before we dive into the example, ensure you have @nestjs/typeorm and typeorm installed in your project. You can install them using the following commands:
npm install --save @nestjs/typeorm typeorm
Advantages of Database Migrations:
Database migrations allow developers to version control changes made to the database schema. Each migration represents a step in the evolution of the database, making it easier to track and manage changes over time.
In a collaborative development environment, multiple developers may be working on different features that require changes to the database schema. Migrations help synchronize these changes seamlessly and reduce conflicts.
Migrations offer the ability to roll back changes in case of issues or errors. This provides a safety net during development and deployment, allowing developers to revert to a previous state if needed.
Migrations ensure that the database schema is consistent across different environments, including development, testing, and production. This consistency reduces the chances of unexpected issues when deploying applications to different environments.
TypeORM can automatically generate migration scripts based on changes in the entity files. This automation simplifies the process of creating and applying migrations, saving developers time and reducing the likelihood of human error.
Disadvantages of Database Migrations:
Implementing and managing database migrations might have a learning curve, especially for developers new to the concept. Understanding how migrations work and how to handle complex scenarios can take time.
While migrations provide a mechanism for tracking changes, errors can still occur during the migration process. Incorrectly defined migrations or issues with the database itself may lead to data loss or corruption.
Applying migrations can introduce some performance overhead, especially in production environments with large databases. Careful consideration is needed when planning and executing migrations to minimize the impact on application performance.
While migrations handle common schema changes well, more complex alterations such as data transformations or combining columns might require additional manual intervention. Developers need to be aware of the limitations and plan accordingly.
Dependency on ORM:
Using database migrations often ties the application to a specific ORM, such as TypeORM. This dependency may limit flexibility in switching to a different ORM or database solution in the future.
领英推荐
Example:
Now, let's walk through a simple example of using TypeORM migrations in a NestJS application, including the process of generating, running, and reverting a migration.
Set up your TypeORM configuration in the ormconfig.json file:
// ormconfig.json
{
"type": "mysql",
"host": "localhost",
"port": 3306,
"username": "root",
"password": "password",
"database": "nestjs_example",
"synchronize": true,
"logging": true,
"entities": ["dist/**/*.entity{.ts,.js}"],
"migrations": ["dist/migrations/*{.ts,.js}"],
"cli": {
"migrationsDir": "src/migrations"
}
}
Update your package.json file with the following scripts:
"scripts": {
"typeorm": "ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli.js",
"typeorm:migrate": "npm run typeorm -- migration:run",
"typeorm:revert": "npm run typeorm -- migration:revert",
"typeorm:generate": "npm run typeorm -- migration:generate -n",
"typeorm:create": "npm run typeorm -- migration:create -n"
}
With these scripts, you can create new migrations using npm run typeorm:create YourMigrationName. The generated migration file can then be customized as needed before applying it to the database.
Define a simple User entity in user.entity.ts:
// user.entity.ts
import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number;
@Column()
username: string;
@Column()
email: string;
}
Use the TypeORM CLI to generate a migration for the User entity:
npx typeorm migration:generate -n CreateUserTable
Execute the generated migration to apply changes to the database:
npx typeorm migration:run
If needed, you can revert the last migration:
npx typeorm migration:revert
Now, you have successfully created, applied, and reverted a migration for the User table in your database.
Migration in Nest JS GitHub Link: ?? (CodeWithAliHamza)
Conclusion:
In conclusion, leveraging TypeORM for database migrations in a NestJS application comes with several advantages and some potential challenges. With careful planning, testing, and documentation, developers can ensure a smooth and reliable evolution of their database schema over time, including the ability to revert changes when necessary.
Follow Me:
#nestjs #migration #nodejs #typeorm #webdevelopment #database #syedalihamzazaidi #expressjs #programming #coding #javascript
Happy Learning ??
PMP? -Software Developer
2 个月got Not enough non-option arguments: got 0, need at least 1 for npx typeorm migration:generate -n CreateUserTable also I think you need to register the config inside app.module