Installation
Chapter 4: TypeORM Installation & Configuration
Section titled “Chapter 4: TypeORM Installation & Configuration”Setting Up TypeORM in Your Project
Section titled “Setting Up TypeORM in Your Project”4.1 Installation Overview
Section titled “4.1 Installation Overview” TypeORM Installation Flow ================================================================================
Step 1: Install Dependencies +-------------------+ | npm install | | typeorm | | reflect-metadata | | database-driver | +-------------------+ | v Step 2: Configure TypeScript +-------------------+ | tsconfig.json | | - decorators | | - emit metadata | +-------------------+ | v Step 3: Create DataSource +-------------------+ | data-source.ts | | - connection | | - entities | | - migrations | +-------------------+ | v Step 4: Initialize in App +-------------------+ | app.module.ts | | or index.ts | +-------------------+
================================================================================4.2 Installing TypeORM
Section titled “4.2 Installing TypeORM”For Standalone Projects
Section titled “For Standalone Projects”# Install TypeORM corenpm install typeorm reflect-metadata
# Install database driver (choose one)npm install pg # PostgreSQL (recommended)npm install mysql2 # MySQLnpm install sqlite3 # SQLitenpm install better-sqlite3 # SQLite (better performance)npm install mongodb # MongoDBnpm install oracledb # Oraclenpm install mssql # Microsoft SQL ServerFor NestJS Projects
Section titled “For NestJS Projects”# Create new NestJS projectnpm i -g @nestjs/clinest new my-projectcd my-project
# Install TypeORM for NestJSnpm install typeorm @nestjs/typeorm @nestjs/config
# Install database drivernpm install pg
# Install validation (recommended)npm install class-validator class-transformer4.3 TypeScript Configuration
Section titled “4.3 TypeScript Configuration”TypeORM requires specific TypeScript compiler options.
{ "compilerOptions": { // Required for TypeORM decorators "experimentalDecorators": true, "emitDecoratorMetadata": true,
// Required for proper type reflection "strictPropertyInitialization": false,
// Recommended settings "strict": true, "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true,
// Output configuration "outDir": "./dist", "rootDir": "./src",
// Module resolution "moduleResolution": "node", "module": "commonjs", "target": "ES2021",
// Source maps for debugging "sourceMap": true }, "include": ["src/**/*"], "exclude": ["node_modules", "dist"]}Why These Settings Matter
Section titled “Why These Settings Matter” TypeScript Configuration Explained +------------------------------------------------------------------+ | | | experimentalDecorators: true | | +----------------------------------------------------------+ | | | Enables @Entity(), @Column() and other decorators | | | | Without this, decorators will cause compile errors | | | +----------------------------------------------------------+ | | | | emitDecoratorMetadata: true | | +----------------------------------------------------------+ | | | Allows TypeORM to infer column types from TypeScript | | | | @Column() name: string; --> TypeORM knows it's VARCHAR | | | +----------------------------------------------------------+ | | | | strictPropertyInitialization: false | | +----------------------------------------------------------+ | | | Allows class properties without initial values | | | | class User { name: string; } // OK without = '' | | | +----------------------------------------------------------+ | | | +------------------------------------------------------------------+4.4 DataSource Configuration
Section titled “4.4 DataSource Configuration”Standalone Configuration
Section titled “Standalone Configuration”import { DataSource } from 'typeorm';import { User } from './entities/user.entity';import { Post } from './entities/post.entity';
export const AppDataSource = new DataSource({ type: 'postgres', // Database type host: 'localhost', // Database host port: 5432, // Database port username: 'postgres', // Database username password: 'password', // Database password database: 'my_app', // Database name
// Entities entities: [User, Post], // Or use: ['src/entities/**/*.ts']
// Migrations migrations: ['src/migrations/**/*.ts'], migrationsRun: false, // Auto-run migrations on startup
// Synchronization (development only!) synchronize: false, // NEVER use true in production!
// Logging logging: true, // Log SQL queries
// Connection pool poolSize: 10, // Number of connections in pool});NestJS Configuration
Section titled “NestJS Configuration”import { TypeOrmModuleOptions } from '@nestjs/typeorm';import { ConfigService } from '@nestjs/config';
export const getDatabaseConfig = ( configService: ConfigService): TypeOrmModuleOptions => ({ type: 'postgres', host: configService.get('DB_HOST', 'localhost'), port: configService.get('DB_PORT', 5432), username: configService.get('DB_USERNAME', 'postgres'), password: configService.get('DB_PASSWORD', 'password'), database: configService.get('DB_NAME', 'my_app'),
entities: [__dirname + '/../**/*.entity{.ts,.js}'],
synchronize: configService.get('NODE_ENV') === 'development', logging: configService.get('NODE_ENV') === 'development',
// Connection pool settings extra: { max: 20, // Maximum connections idleTimeoutMillis: 30000, // Close idle connections after 30s connectionTimeoutMillis: 2000, // Connection timeout },});import { Module } from '@nestjs/common';import { TypeOrmModule } from '@nestjs/typeorm';import { ConfigModule, ConfigService } from '@nestjs/config';import { getDatabaseConfig } from './config/database.config';import { UsersModule } from './users/users.module';
@Module({ imports: [ // Load environment variables ConfigModule.forRoot({ isGlobal: true, envFilePath: '.env', }),
// Configure TypeORM TypeOrmModule.forRootAsync({ imports: [ConfigModule], inject: [ConfigService], useFactory: getDatabaseConfig, }),
// Feature modules UsersModule, ],})export class AppModule {}4.5 Environment Configuration
Section titled “4.5 Environment Configuration”Using .env Files
Section titled “Using .env Files”# .env (never commit this file!)DB_TYPE=postgresDB_HOST=localhostDB_PORT=5432DB_USERNAME=postgresDB_PASSWORD=your_secure_passwordDB_NAME=my_app
# EnvironmentNODE_ENV=development
# Additional settingsDB_SYNCHRONIZE=falseDB_LOGGING=trueDB_POOL_SIZE=10# .env.example (commit this file)DB_TYPE=postgresDB_HOST=localhostDB_PORT=5432DB_USERNAME=postgresDB_PASSWORD=DB_NAME=my_appNODE_ENV=developmentDB_SYNCHRONIZE=falseDB_LOGGING=trueDB_POOL_SIZE=10Configuration with Environment Variables
Section titled “Configuration with Environment Variables”import { DataSourceOptions } from 'typeorm';
export const databaseConfig: DataSourceOptions = { type: (process.env.DB_TYPE as 'postgres') || 'postgres', host: process.env.DB_HOST || 'localhost', port: parseInt(process.env.DB_PORT || '5432', 10), username: process.env.DB_USERNAME || 'postgres', password: process.env.DB_PASSWORD || 'password', database: process.env.DB_NAME || 'my_app',
entities: ['dist/entities/**/*.js'], migrations: ['dist/migrations/**/*.js'],
synchronize: process.env.DB_SYNCHRONIZE === 'true', logging: process.env.DB_LOGGING === 'true',};4.6 Database-Specific Configuration
Section titled “4.6 Database-Specific Configuration”PostgreSQL Configuration
Section titled “PostgreSQL Configuration”import { DataSource } from 'typeorm';
export const AppDataSource = new DataSource({ type: 'postgres', host: 'localhost', port: 5432, username: 'postgres', password: 'password', database: 'my_app',
// PostgreSQL-specific options schema: 'public', // Default schema ssl: false, // SSL connection uuidExtension: 'uuid-ossp', // UUID extension
entities: ['src/entities/**/*.ts'], migrations: ['src/migrations/**/*.ts'],});MySQL Configuration
Section titled “MySQL Configuration”import { DataSource } from 'typeorm';
export const AppDataSource = new DataSource({ type: 'mysql', host: 'localhost', port: 3306, username: 'root', password: 'password', database: 'my_app',
// MySQL-specific options charset: 'utf8mb4', // Character set timezone: '+00:00', // Server timezone
entities: ['src/entities/**/*.ts'], migrations: ['src/migrations/**/*.ts'],});SQLite Configuration
Section titled “SQLite Configuration”import { DataSource } from 'typeorm';
export const AppDataSource = new DataSource({ type: 'better-sqlite3', // or 'sqlite' database: 'my_app.db', // File path or ':memory:'
entities: ['src/entities/**/*.ts'], migrations: ['src/migrations/**/*.ts'],});4.7 Connection Initialization
Section titled “4.7 Connection Initialization”Standalone Application
Section titled “Standalone Application”import 'reflect-metadata';import { AppDataSource } from './data-source';
async function bootstrap() { try { // Initialize connection await AppDataSource.initialize(); console.log('Database connection established');
// Your application logic here // ...
} catch (error) { console.error('Database connection failed:', error); process.exit(1); }}
bootstrap();NestJS Application
Section titled “NestJS Application”import { NestFactory } from '@nestjs/core';import { AppModule } from './app.module';
async function bootstrap() { const app = await NestFactory.create(AppModule);
// Enable validation globally app.useGlobalPipes( new ValidationPipe({ whitelist: true, transform: true, }), );
await app.listen(3000); console.log('Application running on port 3000');}
bootstrap();4.8 Connection Pool Configuration
Section titled “4.8 Connection Pool Configuration” Connection Pool Explained +------------------------------------------------------------------+ | | | Application | | +------------------------+ | | | Request 1 | | | | Request 2 | | | | Request 3 | | | | ... | | | +------------------------+ | | | | | v | | +------------------------+ | | | Connection Pool | | | | (10 connections) | | | | | | | | [C1] [C2] [C3] ... [C10] | | | | | | | | | +---|----|----|---------|------------------------------------+ | | | | | | | | v v v v | | +-----------------------------------+ | | | Database | | | +-----------------------------------+ | | | | Benefits: | | - Reuse connections (no reconnect overhead) | | - Limit concurrent connections | | - Better performance under load | | | +------------------------------------------------------------------+Pool Configuration Options
Section titled “Pool Configuration Options”import { DataSource } from 'typeorm';
export const AppDataSource = new DataSource({ type: 'postgres', // ... other options
// Connection pool settings poolSize: 10, // Number of connections
// Advanced pool settings (via extra) extra: { max: 20, // Maximum connections in pool min: 5, // Minimum connections in pool idleTimeoutMillis: 30000, // Close idle connections after 30s connectionTimeoutMillis: 2000, // Error if can't connect in 2s },});4.9 Multiple Database Connections
Section titled “4.9 Multiple Database Connections”import { Module } from '@nestjs/common';import { TypeOrmModule } from '@nestjs/typeorm';
@Module({ imports: [ // Primary database TypeOrmModule.forRoot({ name: 'primary', type: 'postgres', host: 'localhost', port: 5432, username: 'postgres', password: 'password', database: 'primary_db', entities: [__dirname + '/entities/**/*.entity{.ts,.js}'], }),
// Secondary database TypeOrmModule.forRoot({ name: 'secondary', type: 'postgres', host: 'localhost', port: 5433, username: 'postgres', password: 'password', database: 'secondary_db', entities: [__dirname + '/entities/**/*.entity{.ts,.js}'], }), ],})export class AppModule {}Using Multiple Connections in Services
Section titled “Using Multiple Connections in Services”import { Module } from '@nestjs/common';import { TypeOrmModule } from '@nestjs/typeorm';import { User } from './user.entity';import { UsersService } from './users.service';import { UsersController } from './users.controller';
@Module({ imports: [ // Specify which connection to use TypeOrmModule.forFeature([User], 'primary'), ], controllers: [UsersController], providers: [UsersService],})export class UsersModule {}4.10 Logging Configuration
Section titled “4.10 Logging Configuration”import { DataSource, Logger } from 'typeorm';
// Custom loggerclass CustomLogger implements Logger { logQuery(query: string, parameters?: any[]) { console.log(`[QUERY] ${query}`); if (parameters) { console.log(`[PARAMS] ${JSON.stringify(parameters)}`); } }
logMigration(message: string) { console.log(`[MIGRATION] ${message}`); }
logSchemaBuild(message: string) { console.log(`[SCHEMA] ${message}`); }
log(level: 'log' | 'info' | 'warn', message: any) { console.log(`[${level.toUpperCase()}] ${message}`); }}
export const AppDataSource = new DataSource({ type: 'postgres', // ... other options
// Logging options logging: true, // Enable all logging // OR logging: ['query', 'error', 'migration'], // Selective logging
// Custom logger logger: new CustomLogger(),});4.11 CLI Configuration
Section titled “4.11 CLI Configuration”// ormconfig.json (alternative to programmatic config){ "type": "postgres", "host": "localhost", "port": 5432, "username": "postgres", "password": "password", "database": "my_app", "entities": ["src/entities/**/*.ts"], "migrations": ["src/migrations/**/*.ts"], "cli": { "entitiesDir": "src/entities", "migrationsDir": "src/migrations", "subscribersDir": "src/subscribers" }}TypeORM CLI Commands
Section titled “TypeORM CLI Commands”# Initialize new projecttypeorm init --name my-project --database postgres
# Create entitytypeorm entity:create -n User
# Create migrationtypeorm migration:create -n CreateUserTable
# Create subscribertypeorm subscriber:create -n UserSubscriber
# Run migrationstypeorm migration:run
# Revert migrationtypeorm migration:revert
# Sync schema (development only!)typeorm schema:sync
# Drop schematypeorm schema:drop
# Generate migration from entity changestypeorm migration:generate -n AddUserEmail4.12 Project Structure After Setup
Section titled “4.12 Project Structure After Setup” Recommended Project Structure +------------------------------------------------------------------+ | | | my-project/ | | +----------------------------------------------------------+ | | | | | | | src/ | | | | +----------------------------------------------------+ | | | | | | | | | | | config/ | | | | | | +----------------------------------------------+ | | | | | | | database.config.ts | | | | | | | +----------------------------------------------+ | | | | | | | | | | | | entities/ | | | | | | +----------------------------------------------+ | | | | | | | user.entity.ts | | | | | | | | post.entity.ts | | | | | | | +----------------------------------------------+ | | | | | | | | | | | | migrations/ | | | | | | +----------------------------------------------+ | | | | | | | 1234567890-CreateUser.ts | | | | | | | +----------------------------------------------+ | | | | | | | | | | | | modules/ | | | | | | +----------------------------------------------+ | | | | | | | users/ | | | | | | | | +------------------------------------------+ | | | | | | | | | users.module.ts | | | | | | | | | | users.controller.ts | | | | | | | | | | users.service.ts | | | | | | | | | | dto/ | | | | | | | | | | +--------------------------------------+ | | | | | | | | | | | create-user.dto.ts | | | | | | | | | | | | update-user.dto.ts | | | | | | | | | | | +--------------------------------------+ | | | | | | | | | +------------------------------------------+ | | | | | | | +----------------------------------------------+ | | | | | | | | | | | | data-source.ts | | | | | | app.module.ts | | | | | | main.ts | | | | | +----------------------------------------------------+ | | | | | | | | .env | | | | .env.example | | | | tsconfig.json | | | | package.json | | | +----------------------------------------------------------+ | | | +------------------------------------------------------------------+4.13 Common Installation Issues
Section titled “4.13 Common Installation Issues”Issue 1: Decorators Not Working
Section titled “Issue 1: Decorators Not Working”Error: Unable to resolve signature of class decoratorSolution: Ensure experimentalDecorators and emitDecoratorMetadata are enabled in tsconfig.json.
Issue 2: Connection Refused
Section titled “Issue 2: Connection Refused”Error: connect ECONNREFUSED 127.0.0.1:5432Solution:
- Verify database is running
- Check host and port in configuration
- Verify firewall settings
Issue 3: Authentication Failed
Section titled “Issue 3: Authentication Failed”Error: password authentication failed for user "postgres"Solution:
- Verify username and password
- Check database user permissions
- Check
pg_hba.conffor PostgreSQL
Issue 4: Entity Metadata Not Found
Section titled “Issue 4: Entity Metadata Not Found”Error: No metadata for "User" was foundSolution:
- Ensure entity is registered in DataSource
- Check entity path pattern
- Verify
@Entity()decorator is present
4.14 Summary
Section titled “4.14 Summary” Installation Checklist +------------------------------------------------------------------+ | | | [ ] Install typeorm and reflect-metadata | | [ ] Install database driver (pg, mysql2, etc.) | | [ ] Configure tsconfig.json (decorators enabled) | | [ ] Create data-source.ts or database.config.ts | | [ ] Set up .env file with database credentials | | [ ] Configure connection pool settings | | [ ] Initialize connection in app.module.ts or index.ts | | [ ] Test connection with simple query | | | +------------------------------------------------------------------+Next Chapter
Section titled “Next Chapter”Chapter 5: Connection & DataSource Setup
Last Updated: February 2026