Working with Databases in TypeScript: PostgreSQL and MongoDB for Beginners

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Working with Databases in TypeScript: PostgreSQL and MongoDB for Beginners

\n\n

Modern web development rarely goes without databases. TypeScript, as a strictly typed superset of JavaScript, provides excellent opportunities for safe and predictable data handling. In this article, we will look at how to connect and use two popular databases — the relational PostgreSQL and the document-oriented MongoDB — in TypeScript projects. The material is intended for beginner developers familiar with the basics of TypeScript and Node.js.

\n\n

1. Environment Setup and Dependency Installation

\n\n

Before starting, make sure you have Node.js and npm installed. To work with TypeScript, install the compiler and types for Node.js:

\n\n
npm install -g typescript\nnpm init -y\nnpm install typescript @types/node --save-dev\nnpx tsc --init
\n\n

To work with databases, we will use popular libraries:

\n
    \n
  • TypeORM — ORM for PostgreSQL (and other SQL databases)
  • \n
  • Mongoose — ODM for MongoDB
  • \n
\n\n

Install them in your project:

\n\n
npm install typeorm reflect-metadata pg\nnpm install mongoose
\n\n

Don't forget to add "experimentalDecorators": true and "emitDecoratorMetadata": true to the tsconfig.json file.

\n\n

2. Working with PostgreSQL via TypeORM

\n\n

PostgreSQL is a powerful relational DBMS. TypeORM allows you to work with it through entities and repositories, making the code clean and typed.

\n\n

2.1. Creating a Connection and Entity

\n\n

Let's create a data-source.ts file for configuring the connection:

\n\n
import { DataSource } from "typeorm";\n\nexport const AppDataSource = new DataSource({\n    type: "postgres",\n    host: "localhost",\n    port: 5432,\n    username: "your_user",\n    password: "your_password",\n    database: "your_db",\n    synchronize: true,\n    logging: false,\n    entities: ["src/entity/**/*.ts"],\n});
\n\n

Now let's create a User entity in the src/entity/User.ts file:

\n\n
import { Entity, PrimaryGeneratedColumn, Column } from "typeorm";\n\n@Entity()\nexport class User {\n    @PrimaryGeneratedColumn()\n    id: number;\n\n    @Column()\n    name: string;\n\n    @Column({ unique: true })\n    email: string;\n\n    @Column()\n    age: number;\n}
\n\n

2.2. CRUD Operations with TypeORM

\n\n

Example of creating and retrieving users:

\n\n
import { AppDataSource } from "./data-source";\nimport { User } from "./entity/User";\n\nasync function main() {\n    await AppDataSource.initialize();\n    const userRepository = AppDataSource.getRepository(User);\n\n    // Create\n    const newUser = userRepository.create({\n        name: "Ivan",\n        email: "ivan@example.com",\n        age: 25\n    });\n    await userRepository.save(newUser);\n    console.log("User created:", newUser);\n\n    // Read all\n    const users = await userRepository.find();\n    console.log("All users:", users);\n\n    // Update\n    await userRepository.update({ id: 1 }, { age: 26 });\n\n    // Delete\n    await userRepository.delete({ id: 1 });\n}\n\nmain().catch(console.error);
\n\n

TypeORM automatically generates SQL queries, and TypeScript typing protects against errors at compile time.

\n\n

3. Working with MongoDB via Mongoose

\n\n

MongoDB is a NoSQL database that stores data in a JSON-like format. Mongoose provides schema and validation for TypeScript.

\n\n

3.1. Connection and Schema Definition

\n\n

Let's create a db.ts file for the connection:

\n\n
import mongoose from "mongoose";\n\nexport async function connectDB() {\n    await mongoose.connect("mongodb://localhost:27017/mydb");\n    console.log("Connected to MongoDB");\n}

Blogs

Book Recommendations