Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Installation and Basic Configuration
2.1.
Installing TypeORM
2.2.
Setting Up a Project
2.3.
Configuring TypeORM
3.
Understanding the Core Concepts
3.1.
Entities
3.2.
Repositories
4.
Performing CRUD Operations
4.1.
Creating Data:
4.2.
Reading Data:
4.3.
Updating Data:
4.4.
Deleting Data:
5.
Advanced Features
5.1.
Relations
5.2.
Query Builder
5.3.
Migrations
6.
Frequently Asked Questions
6.1.
How does TypeORM handle database schema changes?
6.2.
Can TypeORM be used with SQL databases only?
6.3.
Is TypeORM suitable for large-scale applications?
7.
Conclusion
Last Updated: Mar 27, 2024
Medium

TypeORM

Author Rinki Deka
0 upvote
Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

TypeORM is a highly influential Object-Relational Mapping (ORM) library for TypeScript and JavaScript, which allows developers to manage database interactions in a more intuitive, object-oriented way. This article will provide an in-depth exploration of TypeORM, offering insights into its installation, configuration, and use, with a focus on TypeScript.

TYPEORM

We'll delve into key concepts, practical examples, and common FAQs to ensure a comprehensive understanding of TypeORM's capabilities and applications.

Installation and Basic Configuration

Installing TypeORM

To get started with TypeORM, you need to have Node.js installed. Then, install TypeORM and a database driver like PostgreSQL, MySQL, or SQLite. For this guide, we'll use PostgreSQL.

npm install typeorm pg

Setting Up a Project

Initialize a new Node.js project if you haven't already:

npm init -y


Then, create a tsconfig.json file for TypeScript configuration:

tsc --init

Configuring TypeORM

Create an ormconfig.json file in your project root. This file will hold your database connection settings:

{
  "type": "postgres",
  "host": "localhost",
  "port": 5432,
  "username": "your_username",
  "password": "your_password",
  "database": "your_database"
}
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Understanding the Core Concepts

Entities

Entities in TypeORM represent tables in your database. They are classes decorated with @Entity, and their properties are decorated with column decorators, representing the columns in the table.

Example:

import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm';
@Entity()
export class User {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  name: string;

  @Column()
  email: string;
}

Repositories

Repositories are abstractions that allow you to manage entity instances. They provide methods like find, findOne, save, etc., to interact with the database.

Working with Data

Creating a Connection

Before performing any database operations, establish a connection:

import { createConnection } from 'typeorm';

createConnection().then(connection => {
  // you can now use the connection
}).catch(error => console.log(error));

Performing CRUD Operations

Creating Data:

To create a new record, use the repository's save method:

import { getRepository } from 'typeorm';
import { User } from './entity/User';

async function createUser() {
  const userRepository = getRepository(User);
  const newUser = userRepository.create({ name: 'John Doe', email: 'john@example.com' });
  await userRepository.save(newUser);
}

Reading Data:

You can read data using various methods like find, findOne, or custom query builders:

async function getUsers() {
  const users = await getRepository(User).find();
  console.log(users);
}

Updating Data:

Update records using the save method or query builder:

async function updateUser(userId: number, updatedData: Partial<User>) {
  const userRepository = getRepository(User);
  await userRepository.update(userId, updatedData);
}

Deleting Data:

Delete records using the remove or delete methods:

async function deleteUser(userId: number) {
  await getRepository(User).delete(userId);
}

Advanced Features

Relations

TypeORM allows defining relationships between tables/entities, like One-to-One, One-to-Many, and Many-to-Many.

Example:

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

  @Column()
  bio: string;
  @OneToOne(() => User)
  @JoinColumn()
  user: User;
}

Query Builder

For complex queries, use the query builder:

const users = await getRepository(User)
  .createQueryBuilder("user")
  .where("user.name = :name", { name: "John" })
  .getMany();

Migrations

Migrations are a way to manage database schema changes. TypeORM provides commands to generate and run migrations.

Frequently Asked Questions

How does TypeORM handle database schema changes?

TypeORM handles schema changes through migrations. You can generate migration files that script out changes to the database schema. These migrations can be applied to update the database schema without losing data.

Can TypeORM be used with SQL databases only?

No, TypeORM supports both SQL and NoSQL databases, although its functionality with NoSQL databases like MongoDB is more limited compared to SQL databases.

Is TypeORM suitable for large-scale applications?

Yes, TypeORM is suitable for both small and large-scale applications. Its ability to handle complex queries, relations, and migrations makes it a robust choice for enterprise-level applications.

Conclusion

TypeORM offers a powerful, efficient, and elegant way to interact with databases in TypeScript. By abstracting database interactions into familiar, object-oriented code, it significantly simplifies database management tasks. Whether you're building a small application or an enterprise-level system, TypeORM stands out as an essential tool in your development arsenal. This guide has provided a comprehensive overview of TypeORM, from setup and configuration to advanced features and best practices. By mastering TypeORM, developers can significantly enhance their productivity and the reliability of their applications.

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. 

Also, check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Previous article
The package.json guide
Next article
Node JS Projects
Live masterclass