Working with Databases in TypeScript: PostgreSQL and MongoDB for Beginners
\n\nModern 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\n1. Environment Setup and Dependency Installation
\n\nBefore starting, make sure you have Node.js and npm installed. To work with TypeScript, install the compiler and types for Node.js:
\n\nnpm install -g typescript\nnpm init -y\nnpm install typescript @types/node --save-dev\nnpx tsc --init\n\nTo work with databases, we will use popular libraries:
\n- \n
- TypeORM — ORM for PostgreSQL (and other SQL databases) \n
- Mongoose — ODM for MongoDB \n
Install them in your project:
\n\nnpm install typeorm reflect-metadata pg\nnpm install mongoose\n\nDon't forget to add "experimentalDecorators": true and "emitDecoratorMetadata": true to the tsconfig.json file.
2. Working with PostgreSQL via TypeORM
\n\nPostgreSQL is a powerful relational DBMS. TypeORM allows you to work with it through entities and repositories, making the code clean and typed.
\n\n2.1. Creating a Connection and Entity
\n\nLet's create a data-source.ts file for configuring the connection:
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\nNow let's create a User entity in the src/entity/User.ts file:
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\n2.2. CRUD Operations with TypeORM
\n\nExample of creating and retrieving users:
\n\nimport { 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\nTypeORM automatically generates SQL queries, and TypeScript typing protects against errors at compile time.
\n\n3. Working with MongoDB via Mongoose
\n\nMongoDB is a NoSQL database that stores data in a JSON-like format. Mongoose provides schema and validation for TypeScript.
\n\n3.1. Connection and Schema Definition
\n\nLet's create a db.ts file for the connection:
import mongoose from "mongoose";\n\nexport async function connectDB() {\n await mongoose.connect("mongodb://localhost:27017/mydb");\n console.log("Connected to MongoDB");\n}