How to Use TypeORM with NestJS: Simple Setup Guide
To use
TypeORM with NestJS, install the @nestjs/typeorm package and configure the TypeOrmModule in your root module with database connection options. Then, define your entities and inject repositories using @InjectRepository in your services to interact with the database.Syntax
Here is the basic syntax to set up TypeORM in a NestJS application:
TypeOrmModule.forRoot(): Configures the database connection globally.TypeOrmModule.forFeature([Entity]): Registers entities for injection in modules.@InjectRepository(Entity): Injects the repository for database operations.
typescript
import { Module } from '@nestjs/common'; import { TypeOrmModule } from '@nestjs/typeorm'; import { User } from './user.entity'; import { UsersService } from './users.service'; @Module({ imports: [ TypeOrmModule.forRoot({ type: 'postgres', host: 'localhost', port: 5432, username: 'user', password: 'pass', database: 'testdb', entities: [User], synchronize: true, }), TypeOrmModule.forFeature([User]), ], providers: [UsersService], }) export class AppModule {}
Example
This example shows a simple NestJS service using TypeORM to manage a User entity with basic CRUD operations.
typescript
import { Injectable } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { Repository } from 'typeorm'; import { User } from './user.entity'; @Injectable() export class UsersService { constructor( @InjectRepository(User) private usersRepository: Repository<User>, ) {} async createUser(name: string): Promise<User> { const user = this.usersRepository.create({ name }); return this.usersRepository.save(user); } async findAll(): Promise<User[]> { return this.usersRepository.find(); } } // user.entity.ts import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm'; @Entity() export class User { @PrimaryGeneratedColumn() id: number; @Column() name: string; }
Output
When calling createUser('Alice'), a new user with name 'Alice' is saved to the database. findAll() returns all users.
Common Pitfalls
Common mistakes when using TypeORM with NestJS include:
- Not importing
TypeOrmModule.forFeature()in the module where the repository is injected. - Forgetting to add entities to
forRootconfiguration, causing errors finding tables. - Setting
synchronize: truein production, which can lead to data loss. - Not awaiting async database calls, leading to unexpected behavior.
typescript
/* Wrong: Missing forFeature import */ @Module({ imports: [TypeOrmModule.forRoot({ /* config */ })], providers: [UsersService], }) export class UsersModule {} /* Right: Include forFeature with entities */ @Module({ imports: [ TypeOrmModule.forRoot({ /* config */ }), TypeOrmModule.forFeature([User]), ], providers: [UsersService], }) export class UsersModule {}
Quick Reference
| Concept | Description |
|---|---|
| TypeOrmModule.forRoot() | Sets up database connection globally |
| TypeOrmModule.forFeature([Entity]) | Registers entities for repository injection |
| @InjectRepository(Entity) | Injects repository for database operations |
| Entity | Class decorated to represent a database table |
| Repository | Provides methods to query and manipulate entities |
Key Takeaways
Import TypeOrmModule.forRoot() with your database config in the root module.
Use TypeOrmModule.forFeature() to register entities in feature modules.
Inject repositories with @InjectRepository(Entity) to access database methods.
Avoid using synchronize: true in production to prevent data loss.
Always await async database calls to ensure correct behavior.