TypeORM works smoothly with NestJS because both follow similar design ideas. This makes building database apps easier and faster.
Why TypeORM integrates seamlessly with NestJS
import { Module } from '@nestjs/common'; import { TypeOrmModule } from '@nestjs/typeorm'; @Module({ imports: [ TypeOrmModule.forRoot({ type: 'postgres', host: 'localhost', port: 5432, username: 'user', password: 'pass', database: 'testdb', entities: [__dirname + '/**/*.entity{.ts,.js}'], synchronize: true, }), ], }) export class AppModule {}
TypeOrmModule.forRoot() sets up the database connection in NestJS.
Entities are classes that represent database tables, decorated with @Entity.
import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm'; @Entity() export class User { @PrimaryGeneratedColumn() id: number; @Column() name: string; }
import { Injectable } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { Repository } from 'typeorm'; import { User } from './user.entity'; @Injectable() export class UserService { constructor( @InjectRepository(User) private userRepository: Repository<User>, ) {} findAll() { return this.userRepository.find(); } }
This example shows a simple NestJS module using TypeORM to connect to an in-memory SQLite database. It defines a User entity and a service to get all users. The integration uses decorators and dependency injection, making database work easy and clean.
import { Module } from '@nestjs/common'; import { TypeOrmModule } from '@nestjs/typeorm'; import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm'; import { Injectable } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { Repository } from 'typeorm'; @Entity() export class User { @PrimaryGeneratedColumn() id: number; @Column() name: string; } @Injectable() export class UserService { constructor( @InjectRepository(User) private userRepository: Repository<User>, ) {} async findAll() { return this.userRepository.find(); } } @Module({ imports: [ TypeOrmModule.forRoot({ type: 'sqlite', database: ':memory:', entities: [User], synchronize: true, }), TypeOrmModule.forFeature([User]), ], providers: [UserService], }) export class AppModule {}
TypeORM uses decorators that fit well with NestJS's style.
Dependency injection in NestJS makes using repositories simple.
Automatic synchronization helps during development but should be used carefully in production.
TypeORM and NestJS share design patterns that make them work well together.
Using TypeORM in NestJS lets you write clean, organized database code.
Decorators and dependency injection simplify database access in NestJS apps.