Introduction to Working with Databases in TypeScript
TypeScript is a strictly typed extension of JavaScript that adds static typing and modern language features. When developing server-side applications in TypeScript, there is often a need to interact with databases. Two of the most popular solutions are the relational DBMS PostgreSQL and the document-oriented MongoDB. In this article, we will look at how to effectively work with both databases in TypeScript using proven libraries and best practices.
Environment Setup and Dependency Installation
Before starting, make sure you have Node.js and npm installed. Create a new project and install the necessary packages:
mkdir typescript-db-examplecd typescript-db-examplenpm init -ynpm install typescript ts-node @types/node --save-devnpx tsc --initFor working with PostgreSQL, we will use TypeORM — a powerful ORM with TypeScript support. For MongoDB — Mongoose.
npm install typeorm reflect-metadata pgnpm install mongooseWorking with PostgreSQL via TypeORM
Configuring the Connection to PostgreSQL
TypeORM supports decorators and active record. Let's create a data-source.ts file for configuration:
import { DataSource } from "typeorm";
export const AppDataSource = new DataSource({ type: "postgres", host: "localhost", port: 5432, username: "your_username", password: "your_password", database: "test_db", synchronize: true, logging: false, entities: ["src/entity/**/*.ts"], migrations: [], subscribers: [],});Creating an Entity
Let's define a user model using decorators:
import { Entity, PrimaryGeneratedColumn, Column } from "typeorm";
@Entity()export class User { @PrimaryGeneratedColumn() id: number;
@Column() firstName: string;
@Column() lastName: string;
@Column({ unique: true }) email: string;
@Column({ default: true }) isActive: boolean;}CRUD Operations with PostgreSQL
Let's perform basic database operations:
import { AppDataSource } from "./data-source";import { User } from "./entity/User";
async function main() { await AppDataSource.initialize(); const userRepository = AppDataSource.getRepository(User);
// CREATE const newUser = userRepository.create({ firstName: "Ivan", lastName: "Petrov", email: "ivan@example.com" }); await userRepository.save(newUser);
// READ const users = await userRepository.find(); console.log("All users:", users);
// UPDATE const userToUpdate = await userRepository.findOneBy({ id: 1 }); if (userToUpdate) { userToUpdate.isActive = false; await userRepository.save(userToUpdate); }
// DELETE await userRepository.delete({ id: 1 });}
main().catch(console.error);Working with MongoDB via Mongoose
Connecting to MongoDB
Mongoose provides a convenient schema and validation for MongoDB. Let's set up the connection:
import mongoose, { Schema, Document, Model } from "mongoose";
const MONGO_URI = "mongodb://localhost:27017/test";
mongoose.connect(MONGO_URI) .then(() => console.log("Connected to MongoDB")) .catch(err => console.error("Connection error:", err));Defining the Schema and Model
Let's create an interface for TypeScript and a Mongoose schema:
// Interface for TypeScriptinterface IUser extends Document { firstName: string; lastName: string; email: string; createdAt: Date;}
// Mongoose Schemaconst userSchema = new Schema({ firstName: { type: String, required: true }, lastName: { type: String, required: true }, email: { type: String, required: true, unique: true }, createdAt: { type: Date, default: Date.now }});
// Modelexport const UserModel: Model = mongoose.model("User", userSchema); CRUD Operations with MongoDB
Let's perform basic operations with MongoDB:
import { UserModel } from "./models/User";
async function main() { // CREATE const newUser = new UserModel({ firstName: "Ivan", lastName: "Petrov", email: "ivan@example.com" }); await newUser.save();
// READ const users = await UserModel.find(); console.log("All users:", users);
// UPDATE await UserModel.updateOne({ _id: newUser._id }, { isActive: false });
// DELETE await UserModel.deleteOne({ _id: newUser._id });}
main().catch(console.error);Conclusion
In this article, we looked at the basics of working with PostgreSQL and MongoDB in TypeScript. TypeORM provides a convenient abstraction for relational databases with support for decorators and automatic migration generation. Mongoose, in turn, offers a flexible schema system and validation for MongoDB. The choice between these solutions depends on the specific tasks of your project: PostgreSQL is better suited for structured data with complex relationships, while MongoDB is ideal for flexible document schemas and rapid prototyping.