Skip to content

Introduction


TypeORM is an Object-Relational Mapping (ORM) library for TypeScript and JavaScript that enables developers to work with databases using objects instead of writing raw SQL queries.

TypeORM Overview
================================================================================
+---------------------------+
| Your Application |
| (TypeScript/JavaScript) |
+---------------------------+
|
| Objects/Entities
v
+---------------------------+
| TypeORM |
| +---------------------+ |
| | Entity Manager | |
| +---------------------+ |
| | Query Builder | |
| +---------------------+ |
| | Repository | |
| +---------------------+ |
| | Migrations | |
| +---------------------+ |
+---------------------------+
|
| Translates to SQL
v
+---------------------------+
| Database |
| (PostgreSQL/MySQL/etc.) |
+---------------------------+
================================================================================
FeatureDescription
Type-SafeFull TypeScript support with decorators
Multiple DatabasesMySQL, PostgreSQL, MariaDB, SQLite, MS SQL Server, Oracle, MongoDB
Active Record & Data MapperSupports both patterns
Query BuilderFlexible and powerful query construction
MigrationsDatabase schema versioning
RelationsOne-to-One, One-to-Many, Many-to-Many
Lazy RelationsLoad related data on demand
SubscribersEvent-driven architecture

Raw SQL Approach
+------------------------------------------------------------------+
| |
| const userId = 1; |
| |
| // Manual SQL query construction |
| const query = ` |
| SELECT u.*, p.title, p.content |
| FROM users u |
| LEFT JOIN posts p ON u.id = p.authorId |
| WHERE u.id = ${userId} |
| `; |
| |
| // No type safety |
| const result = await database.query(query); |
| |
| // Manual mapping |
| const user = { |
| id: result[0].id, |
| name: result[0].name, |
| posts: result.map(r => ({ |
| title: r.title, |
| content: r.content |
| })) |
| }; |
| |
| Problems: |
| - SQL injection risk |
| - No type safety |
| - Manual object mapping |
| - Hard to maintain |
| - No schema validation |
| |
+------------------------------------------------------------------+
TypeORM Approach
+------------------------------------------------------------------+
| |
| // Type-safe entity |
| const user = await userRepository.findOne({ |
| where: { id: 1 }, |
| relations: ['posts'] |
| }); |
| |
| // Full TypeScript support |
| console.log(user.name); // Type-checked! |
| console.log(user.posts[0].title); // Type-checked! |
| |
| Benefits: |
| - Type safety throughout |
| - Automatic object mapping |
| - SQL injection protection |
| - Easy to maintain |
| - Schema validation |
| |
+------------------------------------------------------------------+

TypeORM supports two primary patterns for data access:

Active Record Pattern
+------------------------------------------------------------------+
| |
| Entity contains both data and database methods |
| |
| +----------------------------------------------------------+ |
| | User Entity | |
| | | |
| | Properties: Methods: | |
| | - id - save() | |
| | - name - remove() | |
| | - email - find() | |
| | - password - findOne() | |
| | - delete() | |
| | | |
| +----------------------------------------------------------+ |
| |
| Usage: |
| +----------------------------------------------------------+ |
| | | |
| | const user = new User(); | |
| | user.name = 'John'; | |
| | user.email = 'john@example.com'; | |
| | await user.save(); // Method on entity | |
| | | |
| | const users = await User.find(); | |
| | | |
| +----------------------------------------------------------+ |
| |
| Best for: Simple applications, quick prototyping |
| |
+------------------------------------------------------------------+
Data Mapper Pattern
+------------------------------------------------------------------+
| |
| Entity contains only data, Repository handles operations |
| |
| +-------------------+ +-------------------+ |
| | User Entity | | Repository | |
| | | | | |
| | Properties: | | Methods: | |
| | - id | | - save() | |
| | - name | | - find() | |
| | - email | | - findOne() | |
| | - password | | - delete() | |
| | | | - create() | |
| +-------------------+ +-------------------+ |
| |
| Usage: |
| +----------------------------------------------------------+ |
| | | |
| | const user = new User(); | |
| | user.name = 'John'; | |
| | user.email = 'john@example.com'; | |
| | | |
| | await userRepository.save(user); // Via repository | |
| | | |
| | const users = await userRepository.find(); | |
| | | |
| +----------------------------------------------------------+ |
| |
| Best for: Enterprise applications, Clean Architecture |
| |
+------------------------------------------------------------------+

ORM Comparison
+------------------------------------------------------------------+
| |
| Feature | TypeORM | Prisma | Sequelize |
| ------------------|------------|-----------|------------------|
| TypeScript First | Yes | Yes | No |
| Decorators | Yes | No | No |
| Query Builder | Excellent | Good | Good |
| Migrations | Built-in | Built-in | Built-in |
| Active Record | Yes | No | Yes |
| Data Mapper | Yes | Yes | No |
| Raw SQL | Easy | Moderate | Easy |
| Relations | Excellent | Excellent | Good |
| Performance | Good | Good | Good |
| Documentation | Good | Excellent | Good |
| |
+------------------------------------------------------------------+

TypeORM Ecosystem
================================================================================
TypeORM Core
|
+----------------------------+----------------------------+
| | | | |
v v v v v
+------------+ +------------+ +------------+ +------------+ +--------+
| CLI Tool | | Migrations | | CLI | | Extensions | | Docs |
| | | | | Commands | | | | |
| - Generate | | - Create | | - schema: | | - TypeORM | | - API |
| - Create | | - Run | | sync | | Module | | - Docs |
| - Run | | - Revert | | - schema: | | (NestJS) | | - Ex |
| | | | | drop | | | | |
+------------+ +------------+ +------------+ +------------+ +--------+
================================================================================
Terminal window
# Initialize new TypeORM project
typeorm init --name my-project --database postgres
# Generate entity
typeorm entity:create -n User
# Generate migration
typeorm migration:create -n CreateUserTable
# Run migrations
typeorm migration:run
# Revert last migration
typeorm migration:revert
# Sync schema (development only!)
typeorm schema:sync
# Drop schema
typeorm schema:drop

Recommended Scenarios
+------------------------------------------------------------------+
| |
| +------------------+ |
| | NestJS Projects | - First-class integration |
| +------------------+ |
| |
| +------------------+ |
| | Complex Domains | - Rich relationship handling |
| +------------------+ |
| |
| +------------------+ |
| | TypeScript Apps | - Type safety throughout |
| +------------------+ |
| |
| +------------------+ |
| | Multi-Database | - Same API for different DBs |
| +------------------+ |
| |
| +------------------+ |
| | Enterprise Apps | - Migrations, transactions |
| +------------------+ |
| |
+------------------------------------------------------------------+
Alternative Scenarios
+------------------------------------------------------------------+
| |
| +--------------------+ |
| | Simple Queries Only | - Consider raw query builders |
| +--------------------+ - pg, mysql2 directly |
| |
| +--------------------+ |
| | Maximum Performance | - Consider query builders |
| +--------------------+ - Kysely, Slonik |
| |
| +--------------------+ |
| | No-SQL Primary | - TypeORM MongoDB support limited |
| +--------------------+ - Consider Mongoose, Prisma |
| |
| +--------------------+ |
| | Learning Curve | - Consider Prisma for simplicity |
| +--------------------+ |
| |
+------------------------------------------------------------------+

Typical TypeORM Project
+------------------------------------------------------------------+
| |
| src/ |
| ├── entities/ |
| │ ├── User.ts |
| │ ├── Post.ts |
| │ └── Comment.ts |
| │ |
| ├── repositories/ |
| │ ├── UserRepository.ts |
| │ └── PostRepository.ts |
| │ |
| ├── migrations/ |
| │ ├── 1234567890-CreateUser.ts |
| │ └── 1234567891-CreatePost.ts |
| │ |
| ├── subscribers/ |
| │ └── UserSubscriber.ts |
| │ |
| ├── data-source.ts |
| └── index.ts |
| |
+------------------------------------------------------------------+

TypeORM Request Flow
================================================================================
1. Define Entity 2. Create Repository
+------------------+ +------------------+
| @Entity() | | @EntityRepository|
| class User { | | class UserRepo |
| @PrimaryColumn | | extends Repo |
| id: number; | | { |
| | | findByName() |
| @Column() | | } |
| name: string; | +------------------+
+------------------+
| |
| |
v v
3. TypeORM Creates Table 4. Use in Application
+------------------+ +------------------+
| users | | const users = |
| -------- | | await userRepo |
| id (PK) | | .find(); |
| name | +------------------+
+------------------+
================================================================================

TypeORM Key Concepts
+------------------------------------------------------------------+
| |
| Concept | Description |
| -----------------|------------------------------------------- |
| Entity | Class mapped to database table |
| Column | Property mapped to table column |
| Primary Column | Primary key column |
| Repository | Data access object for entity |
| Query Builder | Programmatic SQL query construction |
| Migration | Database schema version control |
| Relation | Connection between entities |
| Subscriber | Entity lifecycle event listener |
| DataSource | Database connection configuration |
| Transaction | Atomic database operations |
| |
+------------------------------------------------------------------+

Terminal window
# Install TypeORM and database driver
npm install typeorm reflect-metadata
# Choose your database driver
npm install pg # PostgreSQL
npm install mysql2 # MySQL
npm install sqlite3 # SQLite
npm install better-sqlite3 # SQLite (better performance)
npm install mongodb # MongoDB
# For NestJS integration
npm install @nestjs/typeorm @nestjs/config

Chapter 2: TypeScript Foundations for TypeORM


Last Updated: February 2026