How to use TypeORM in Node.js

Using TypeORM in Node.js provides a modern, TypeScript-first Object-Relational Mapping solution with decorators and advanced features for enterprise database management. As the creator of CoreUI with extensive Node.js experience since 2014, I’ve implemented TypeORM in numerous enterprise applications requiring type-safe database operations and complex relational data modeling. The most effective approach involves defining entities with decorators, configuring database connections with migration support, and using repositories for data access patterns. This method provides compile-time type safety while offering advanced features like lazy loading, cascade operations, and automatic schema synchronization.

Install TypeORM with database driver and configure entities with decorators for type-safe database operations in Node.js.

import { DataSource } from 'typeorm'
import { Entity, PrimaryGeneratedColumn, Column, OneToMany, ManyToOne, CreateDateColumn, UpdateDateColumn } from 'typeorm'

// User entity
@Entity()
export class User {
    @PrimaryGeneratedColumn()
    id: number

    @Column({ unique: true })
    email: string

    @Column()
    name: string

    @Column()
    password: string

    @CreateDateColumn()
    createdAt: Date

    @UpdateDateColumn()
    updatedAt: Date

    @OneToMany(() => Post, post => post.user)
    posts: Post[]
}

// Post entity
@Entity()
export class Post {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    title: string

    @Column('text')
    content: string

    @CreateDateColumn()
    createdAt: Date

    @ManyToOne(() => User, user => user.posts)
    user: User
}

// Database configuration
export const AppDataSource = new DataSource({
    type: 'postgres',
    host: 'localhost',
    port: 5432,
    username: 'username',
    password: 'password',
    database: 'database',
    synchronize: false,
    logging: true,
    entities: [User, Post],
    migrations: ['src/migration/**/*.ts']
})

// Repository usage
async function initializeDatabase() {
    await AppDataSource.initialize()
    console.log('Database connected')
}

async function createUser(userData: Partial<User>): Promise<User> {
    const userRepository = AppDataSource.getRepository(User)
    const user = userRepository.create(userData)
    return await userRepository.save(user)
}

async function findUserWithPosts(id: number): Promise<User> {
    const userRepository = AppDataSource.getRepository(User)
    return await userRepository.findOne({
        where: { id },
        relations: ['posts']
    })
}

This code demonstrates complete TypeORM integration with TypeScript decorators for entity definition, relationship mapping with proper typing, and repository pattern for data access. The setup includes automatic timestamp columns, foreign key relationships, and type-safe query building with compile-time validation. TypeORM provides advanced ORM features while maintaining full TypeScript compatibility and generating optimized SQL queries for complex operations.

Best Practice Note:

This is the TypeORM architecture we use in CoreUI enterprise backend services for type-safe database operations. Always use migrations for production deployments and leverage TypeORM’s query builder for complex queries requiring performance optimization and custom SQL control.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author

Subscribe to our newsletter
Get early information about new products, product updates and blog posts.
How to validate an email address in JavaScript
How to validate an email address in JavaScript

What is globalThis in JavaScript?
What is globalThis in JavaScript?

How to Use Bootstrap Modal in Vue 3 – Clean Integration with CoreUI
How to Use Bootstrap Modal in Vue 3 – Clean Integration with CoreUI

JavaScript Template Literals: Complete Developer Guide
JavaScript Template Literals: Complete Developer Guide

Answers by CoreUI Core Team