Setup PostgreSQL With TypeORM

Setup PostgreSQL With TypeORM

Dec 22, 2021ยท

3 min read

Play this article

What is an ORM ?

ORM Stands For Object Relational Mapping Used To Convert Data Between Incompatible Type System Using Object Oriented Programming Languages Like JavaScript, TypeScript, Python

  • JavaScript
    • Sequelize
    • Prisma
  • TypeScript
    • TypeORM
    • Mikro-ORM
  • Python
    • SQLAlchemy
    • Django ORM

Why TypeORM

If You Know Me, I Am a Big Fan Of TypeScript And I Like Both Mikro-ORM And TypeORM But The Thing With TypeORM That It Is More Of Like TypeScript Syntax. Basically I Like TypeORM Syntax Than Mikro-ORM

Setting Up TypeORM

Creating A Basic Node.js App

npm init
# Yarn
yarn init

Adding TypeScript

npm install -D typescript @types/node nodemon
# Yarn
yarn add -D typescript @types/node nodemon
  • Dependencies
    • typescript - Compiler For TypeScript
    • @types/node - Types For Node.js
    • nodemon - Restarts The Server On Changes

Open Your package.json And Add Scripts To It

"scripts": {
    "start": "node dist/index.js",
    "dev": "nodemon dist/index.js",
    "watch": "tsc -w"

Now We Need A tsconfig.json, So Instead Of Typing tsconfig.json From Scratch Let's Generate It

npx tsconfig.json

Select Node.js When Asked To Enter Your Framework

Run The Application

Create a File src/index.ts And Add This Code To It

console.log('hello world')

Now Open a Terminal And Run watch Command

npm run watch
# Yarn
yarn watch

Open Another Terminal And Run dev Command

npm run dev
# Yarn
yarn dev

You Should See hello world

Add TypeORM

npm install typeorm pg reflect-metadata
# Yarn
yarn add typeorm pg reflect-metadata
  • Dependencies
    • typeorm - Base TypeORM Package
    • pg - Postgres Driver For Node.js
    • reflect-metadata - Required For TypeORM

Now We Can Create A Connection To Our Database Open src/index.ts and add async connection to typeorm

import "reflect-metadata"
const main = async () => {
    console.log('hello world')
main().catch(err => console.error(err))

Now we can use async/await syntax inside main function we can setting up typeorm connection using the createConnection function

// src/index.ts
import "reflect-metadata"
import { createConnection } from "typeorm"
const main = async () => {
    await createConnection({
        type: "postgres", // DATABASE TYPE
        host: "localhost", // DATABASE HOST
        username: "test", // USERNAME
        password: "test", // PASSWORD
        database: "test", // DATABASE
        logging: true, // LOG THE GENERATED SQL
        synchronize: true // FALSE ON PRODUCTION
main().catch(err => console.error(err))

Creating An Entity (Table)

// src/entities/User.ts
import { Entity, PrimaryGeneratedColumn, Column, BaseEntity } from "typeorm";
export class User extends BaseEntity {
    id: string;
    firstName: string;
    lastName: string;
    isActive: boolean;

Now if you open your terminal running the dev command you should see generated SQL



const user = new User({firstName: "Nouman", lastName: "Rahman", isActive: true});


await User.find() // Give All Users
await User.findOne("1") // Give The User With ID ("1")


await User.update({id: 1}, {firstName: "Nouman"}) // Update firstName Of The User With ID ("1")


await User.delete({id: 1}) // Delete The User With ID ("1")

Did you find this article valuable?

Support Nouman Rahman by becoming a sponsor. Any amount is appreciated!