How to Use TypeORM inNode.js A Step-by-StepGuide

How to Use TypeORM in Node.js: A Step-by-Step Guide with Employee CRUD Example

Jun 02, 2025 |

18 minutes read

How to Use TypeORM inNode.js A Step-by-StepGuide

TypeORM for Scalable Node.js Applications

Effective data management is essential for guaranteeing scalability, maintainability, and performance while developing contemporary online applications using Node.js.  Using an Object-Relational Mapping (ORM) tool is one of the best ways to manage database operations in an orderly and systematic fashion.  Using object-oriented concepts, TypeORM is a robust and feature-rich ORM for Node.js that enables developers to work with relational databases.  It is a popular option for enterprise-grade apps since it integrates easily with Express and supports TypeScript right out of the box.  In this comprehensive guide, we’ll show you how to use TypeORM, Node.js, Express, and TypeScript to build a simple employee management system.

Whether you’re learning backend development or looking to streamline your application’s data layer, this guide offers a practical foundation. If you’re looking to build robust backend solutions faster, it’s often beneficial to hire a Node.js developer who is experienced with TypeORM and TypeScript for optimal results.

What is TypeORM?

TypeORM is an open-source ORM (Object Relational Mapper) for TypeScript and JavaScript (ES7, ES6, ES5). It enables you to work with databases like MySQL, PostgreSQL, SQLite, and more using object-oriented code. With TypeORM, you can define database schemas directly in your code using classes and decorators, making development more intuitive and less error-prone.

TypeORM is an ORM that can run in Node.js and is written in TypeScript. It allows you to:

  • Define database tables as TypeScript classes. 
  • Perform CRUD operations easily. 
  • Use decorators to define relations, indexes, and constraints. 
  • Handle migrations.

It supports many databases like MySQL, PostgreSQL, SQLite, and SQL Server.

Prerequisites

Before we dive into the tutorial, make sure you have the following installed:

  • Node.js (v14 or higher recommended)
  • npm or yarn
  • TypeScript
  • A database (e.g., MySQL or PostgreSQL)
  • Basic knowledge of JavaScript/TypeScript

Step 1: Project Setup

Initialize a Node.js project: 

mkdir employee-management
cd employee-management
npm init -y 

This creates a new project directory and initializes package.json.

Install required dependencies: 

npm install express typeorm reflect-metadata mysql2
npm install –save-dev typescript ts-node-dev @types/express

Here’s what each package does:

  • express: Web framework 
  • typeorm: ORM library 
  • reflect-metadata: Required for TypeORM decorators 
  • mysql2: MySQL driver for Node.js 
  • typescript, ts-node-dev, @types/express: TypeScript and dev tools

Create a TypeScript configuration file: 

Create a file named tsconfig.json in the root: 

{
  “compilerOptions”: {
“target”: “ES2020”,
“module”: “commonjs”,
“strict”: true,
“esModuleInterop”: true,
“experimentalDecorators”: true,
“emitDecoratorMetadata”: true,
“outDir”: “./dist”
  },
  “include”: [“src”]

This config enables TypeScript features and support for decorators required by TypeORM.

Step 2: Set up TypeORM Connection

Create a new file src/data-source.ts

import { DataSource } from “typeorm”;
import { Employee } from “./entity/Employee”;

export const AppDataSource = new DataSource({
  type: “mysql”,
  host: “localhost”,
  port: 3306,
  username: “root”,
  password: “your_password”,
  database: “employee_db”,
  synchronize: true,
  logging: false,
  entities: [Employee],
})

This file sets up the connection to the MySQL database using TypeORM.

  • Replace your_password with your actual MySQL password. 
  • synchronize: true automatically syncs your database schema with the entity (in development only).

Step 3: Create the Employee Entity

Create a new file src/entity/Employee.ts

import { Entity, PrimaryGeneratedColumn, Column } from “typeorm”;

@Entity()
export class Employee {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  firstName: string;

  @Column()
  lastName: string;

  @Column()
  email: string;

  @Column()
  position: string;

This defines the Employee entity class. Each class property becomes a column in the database table.

  • @Entity() marks it as a table 
  • @PrimaryGeneratedColumn() creates an auto-increment ID 
  • @Column() maps the field to a DB column

 Step 4: Create Express Server and API Routes

Create a new file src/index.ts

import express from “express”;
import { AppDataSource } from “./data-source”;
import { Employee } from “./entity/Employee”;

const app = express();
app.use(express.json()); 

We import Express and setup middleware to parse JSON request bodies. 

Initialize the database and start the server: 

AppDataSource.initialize()
  .then(() => {
console.log(“Database connected”); 

This initializes the connection using the data source configuration.

Create a repository for Employee: 

   const employeeRepo = AppDataSource.getRepository(Employee); 

This gives us access to CRUD operations for the Employee entity. 

Route: Create a new employee

app.post(“/employees”, async (req, res) => {
  const employee = employeeRepo.create(req.body);
  const result = await employeeRepo.save(employee);
  res.json(result);
    }); 

This route creates a new employee. create() builds an entity object, and save() persists it to the DB. 

Route: Get all employees 

   app.get(“/employees”, async (_req, res) => {
  const employees = await employeeRepo.find();
  res.json(employees);
    }); 

This route fetches and returns all employee records. 

Route: Get employee by ID 

   app.get(“/employees/:id”, async (req, res) => {
  const employee = await employeeRepo.findOneBy({ id: Number(req.params.id) });
  if (employee) {
    res.json(employee);
  } else {
    res.status(404).json({ message: “Employee not found” });
  }
}); 

This fetches an employee by ID. If not found, it returns a 404 error.

Route: Update employee by ID 

   app.put(“/employees/:id”, async (req, res) => {
  const employee = await employeeRepo.findOneBy({ id: Number(req.params.id) });
  if (employee) {
    employeeRepo.merge(employee, req.body);
    const result = await employeeRepo.save(employee);
    res.json(result);
  } else {
    res.status(404).json({ message: “Employee not found” });
  }
}); 

This updates an existing employee by merging new data and saving it.

Route: Delete employee 

   app.delete(“/employees/:id”, async (req, res) => {
  const result = await employeeRepo.delete(req.params.id);
  res.json(result);
    }); 

This deletes an employee by ID.  

Start Express Server 

   app.listen(3000, () => {
  console.log(“Server started on port 3000”);
    });
  })
  .catch((error) => console.log(“Error connecting to DB”, error)); 

This starts the Express server after the DB connection is successful. 

Testing Your API 

Use Postman or curl to test: 

  • POST /employees – Add employee 
  • GET /employees – Get all employees 
  • GET /employees/:id – Get employee by ID 
  • PUT /employees/:id – Update employee
  • DELETE /employees/:id – Remove employee

TypeORM Simplifies Your Node.js App Development

The Way Forward

TypeORM makes it easier to manage your database operations in Node.js applications using a familiar and maintainable object-oriented approach. With built-in support for TypeScript, decorators, and multiple databases, it’s a solid choice for modern web projects. For businesses seeking scalable and efficient solutions, leveraging professional Node.js development services can significantly streamline the development process. If you’re looking to speed up development or ensure your backend is built following best practices, you might want to hire a Node.js developer with hands-on experience in TypeORM and TypeScript.

Free Consultation

    Jignesh Jadav

    Jignesh is a recognized Assistant Project Manager at iFlair Web Technologies Pvt. Ltd. Jignesh has over 9 years of industry experience, and in his career, he has managed many web development projects that have been delivered on time with high customer satisfaction. His skills include JS expertise including Angular, React, Vue.js, Mean.js, Next.js, Nuxt.js, and Full-stack tech expertise also in project planning, client communication, and team management, which are a great addition to the company's continuous development and success in the technology industry.



    MAP_New

    Global Footprints

    Served clients across the globe from38+ countries

    iFlair Web Technologies
    Privacy Overview

    This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.