Working with Databases in TypeScript: PostgreSQL and MongoDB for Beginners
TypeScript is a strictly typed extension of JavaScript that adds reliability and predictability to your code. When working with databases, TypeScript is especially useful: you can define types for entities, check query correctness at compile time, and avoid many runtime errors. In this article, we will look at how to connect to two of the most popular databases — relational PostgreSQL and document-oriented MongoDB — and perform basic data operations. The material is aimed at beginner developers familiar with the basics of TypeScript.
Environment Setup and Dependency Installation
Before writing code, you need to set up the project. Create a new directory and initialize the project:
mkdir ts-db-examplecd ts-db-examplenpm init -ynpm install typescript @types/node ts-node --save-devnpx tsc --initNow let's install the libraries for working with databases. For PostgreSQL, we will use TypeORM (a popular ORM with good TypeScript support), and for MongoDB — Mongoose (a library for schema modeling and working with MongoDB).
npm install typeorm reflect-metadata pgnpm install mongooseAlso install the types for Node.js and TypeORM settings:
npm install @types/node --save-devIn the tsconfig.json file, be sure to enable the options:
{ "compilerOptions": { "target": "ES2020", "module": "commonjs", "outDir": "./dist", "rootDir": "./src", "strict": true, "esModuleInterop": true, "experimentalDecorators": true, "emitDecoratorMetadata": true }}Now the project structure is ready. Create a src folder and inside it, files for working with each database.
Working with PostgreSQL via TypeORM
Connection Setup
TypeORM allows you to work with databases using decorators and entities. Let's create a file src/postgres.ts and set up a connection to the local PostgreSQL database ts_db:
import "reflect-metadata";import { DataSource } from "typeorm";
export const AppDataSource = new DataSource({ type: "postgres", host: "localhost", port: 5432, username: "postgres", password: "password", database: "ts_db", synchronize: true, // automatically creates tables (development only) logging: false, entities: ["src/entity/**/*.ts"],});Creating an Entity
An entity is a class that maps to a database table. Let's create a folder src/entity and a file User.ts:
import { Entity, PrimaryGeneratedColumn, Column } from "typeorm";
@Entity()export class User { @PrimaryGeneratedColumn() id: number;
@Column({ length: 100 }) name: string;
@Column({ unique: true }) email: string;
@Column({ default: 18 }) age: number;}Performing CRUD Operations
Now let's write functions for creating, reading, updating, and deleting users in the file src/postgres-crud.ts:
import { AppDataSource } from "./postgres";import { User } from "./entity/User";
async function main() { await AppDataSource.initialize(); const userRepository = AppDataSource.getRepository(User);
// CREATE — creating a new user const newUser = userRepository.create({ name: "Ivan Petrov", email: "ivan@example.com", age: 25, }); await userRepository.save(newUser); console.log("User created:", newUser);
// READ — reading all users const allUsers = await userRepository.find(); console.log("All users:", allUsers);
// UPDATE — updating the age of the user with id=1 const userToUpdate =