The Most Popular ORM Choice for Nest
TypeORM in NestJS
TypeORM is a TypeScript-first ORM and Nest's most common pairing. The `@nestjs/typeorm` package gives you a clean module-level integration.
What you'll learn
- Install and import TypeOrmModule.forRoot
- Configure a Postgres connection
- Get a sense of the entity → repository workflow
Nest doesn’t ship a database layer — you choose one. TypeORM is the most
common pick, partly because it was written in TypeScript from day one and
partly because @nestjs/typeorm makes setup feel native.
Install
npm i @nestjs/typeorm typeorm pg You’ll need the driver for your database. pg for Postgres, mysql2 for
MySQL/MariaDB, sqlite3 for SQLite, and so on.
Wire It Up
Register the connection once in AppModule. Every feature module will
share it.
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
@Module({
imports: [
TypeOrmModule.forRoot({
type: 'postgres',
host: 'localhost',
port: 5432,
username: 'postgres',
password: 'secret',
database: 'app',
entities: [__dirname + '/**/*.entity{.ts,.js}'],
synchronize: false,
}),
],
})
export class AppModule {} synchronize: true auto-creates tables from your entities. It’s wonderful
for prototyping and dangerous in production — one rename and your data
is gone. Use migrations for any real environment.
The Workflow at a Glance
The pieces you’ll meet over the next few lessons:
- Entity — a class decorated with
@Entity()that maps to a table. - Repository — Nest auto-creates one per entity. It has methods like
find,findOne,save,delete. - Service — injects the repository and exposes business operations.
@Injectable()
export class UsersService {
constructor(
@InjectRepository(User) private readonly repo: Repository<User>,
) {}
findAll() {
return this.repo.find();
}
} That Repository<User> is the heart of it — a generic class you’ll be
seeing a lot.