Working with Databases in JavaScript: PostgreSQL and MongoDB

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

Introduction to Working with Databases in JavaScript

Modern web development in JavaScript is unthinkable without interaction with databases. Node.js provides powerful tools for working with both relational (SQL) and document-oriented (NoSQL) databases. In this article, we will detail the connection and execution of basic operations with the two most popular DBMS in the JavaScript ecosystem: PostgreSQL and MongoDB.

You will learn how to install drivers, configure a connection, perform CRUD operations (Create, Read, Update, Delete), and make the right choice between SQL and NoSQL for your project.



Environment Setup

To work with the examples, you will need Node.js (version 18+) and the npm package manager. Make sure the databases are running locally or are accessible remotely.



1. Working with PostgreSQL in Node.js

PostgreSQL is a powerful open-source relational database. To work with it in Node.js, we will use the pg library — the official client.



Installation and Connection

npm install pg

Let's create a db.js file to configure the connection pool:

const { Pool } = require('pg');

const pool = new Pool({ user: 'postgres', host: 'localhost', database: 'mydb', password: 'secret', port: 5432,});

module.exports = pool;


CRUD Operations with PostgreSQL

Let's look at basic queries to the users table:



Creating a Table (CREATE)

const createTable = async () => {  const query = `    CREATE TABLE IF NOT EXISTS users (      id SERIAL PRIMARY KEY,      name VARCHAR(100) NOT NULL,      email VARCHAR(255) UNIQUE NOT NULL,      age INTEGER,      created_at TIMESTAMP DEFAULT NOW()    );  `;  await pool.query(query);  console.log('Table users created');};


Inserting Data (INSERT)

const addUser = async (name, email, age) => {  const text = 'INSERT INTO users(name, email, age) VALUES($1, $2, $3) RETURNING *';  const values = [name, email, age];  const res = await pool.query(text, values);  console.log('User added:', res.rows[0]);  return res.rows[0];};

// UsageaddUser('Ivan Petrov', 'ivan@example.com', 30);


Reading Data (SELECT)

const getUsers = async (ageLimit) => {  const res = await pool.query(    'SELECT * FROM users WHERE age > $1 ORDER BY created_at DESC',    [ageLimit]  );  return res.rows;};

// Get users older than 25getUsers(25).then(users => console.log(users));


Updating and Deleting (UPDATE / DELETE)

const updateUser = async (id, newName) => {  const res = await pool.query(    'UPDATE users SET name = $1 WHERE id = $2 RETURNING *',    [newName, id]  );  return res.rows[0];};

const deleteUser = async (id) => { await pool.query('DELETE FROM users WHERE id = $1', [id]); console.log(`User with id ${id} deleted`);};

Important: Always use parameterized queries ($1, $2) to prevent SQL injections.



2. Working with MongoDB in Node.js

MongoDB is the most popular NoSQL database, storing data in JSON-like document format. For working with it, we use the official mongodb driver or the popular ODM library mongoose.



Installation and Connection (using mongoose)

npm install mongoose
const mongoose = require('mongoose');

const connectDB = async () => { try { await mongoose.connect('mongodb://localhost:27017/mydb'); console.log('MongoDB connected'); } catch (error) { console.error('Connection error:', error); }};

connectDB();


Defining a Schema and Model

Blogs

Book Recommendations