How to Use TypeORM in Node.js: A Step-by-Step Guide with Employee CRUD Example Jun 02, 2025 | 18 minutes read 3 Likes TypeORM for Scalable Node.js ApplicationsEffective 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. PrerequisitesBefore we dive into the tutorial, make sure you have the following installed:Node.js (v14 or higher recommended)npm or yarnTypeScriptA database (e.g., MySQL or PostgreSQL)Basic knowledge of JavaScript/TypeScriptStep 1: Project SetupInitialize 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 ConnectionCreate 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 EntityCreate 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 RoutesCreate 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 employeeapp.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 employeeTypeORM Simplifies Your Node.js App Development TypeORM GoThe Way ForwardTypeORM 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 Hire Node.js DeveloperNode.js DevelopmentNode.js Development AgencyTypeORMNode.jsJignesh JadavJun 02 2025Jignesh 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.You may also like Leveraging Node.js Service Providers to Rebuild and Optimize Your Web Applications Read More Mar 05 2025 Optimizing Travel Industry Platforms with Professional Node.js Development Read More Feb 20 2025 Top BigCommerce Development Company for Customized Online Stores Read More Feb 04 2025 Node.js Development Services for Modern Media and Entertainment Platforms Read More Jan 29 2025 15 Must-Know JavaScript Frameworks for Developers Read More Jan 16 2025 Partner with iFlair for Seamless Node.js Development Solutions Read More Jan 09 2025