Working with Databases in JavaScript: PostgreSQL and MongoDB in Practice

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: Why should a developer know SQL and NoSQL?

Modern web development in JavaScript (Node.js) rarely goes without interacting with databases. The choice between relational (PostgreSQL) and document-oriented (MongoDB) DBMS is one of the key architectural tasks. In this article, we will practically examine how to connect to both databases, perform CRUD operations, and choose the right tool for a specific task.

We will use popular libraries: pg for PostgreSQL and mongoose for MongoDB. All code examples are in Node.js.



1. PostgreSQL in Node.js: The Relational Approach

1.1. Connection and Setup

PostgreSQL is a powerful relational DBMS with SQL support. To work with it in Node.js, install the pg package:

npm install pg

Example of connecting to a local database mydb:

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

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

// Testing the connectionpool.query('SELECT NOW()', (err, res) => { if (err) { console.error('Connection error:', err); } else { console.log('Connected to PostgreSQL:', res.rows[0].now); }});


1.2. CRUD Operations (Create, Read, Update, Delete)

Let's create a users table and perform basic operations.

Creating a table:

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

createTable();

Inserting data (INSERT):

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

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

Reading data (SELECT):

const getUsers = async () => {  const res = await pool.query('SELECT * FROM users');  console.log('All users:', res.rows);};

getUsers();

Updating data (UPDATE):

const updateUserAge = async (id, newAge) => {  const query = 'UPDATE users SET age = $1 WHERE id = $2 RETURNING *';  const values = [newAge, id];  const res = await pool.query(query, values);  console.log('User updated:', res.rows[0]);};

updateUserAge(1, 31);

Deleting data (DELETE):

const deleteUser = async (id) => {  const query = 'DELETE FROM users WHERE id = $1 RETURNING *';  const values = [id];  const res = await pool.query(query, values);  console.log('User deleted:', res.rows[0]);};

deleteUser(1);

Note the use of parameterized queries ($1, $2). This protects against SQL injection.



1.3. When to choose PostgreSQL?

  • Strict data structure and integrity support (foreign keys, transactions) are required.
  • Complex JOIN queries and aggregations are needed.
  • Working with financial or mission-critical data.
  • The project uses an ORM like Sequelize or TypeORM.


2. MongoDB in Node.js: NoSQL Flexibility

2.1. Connection via Mongoose

MongoDB is a document-oriented database where data is stored in JSON-like format (BSON). To work with it, install mongoose:

npm install mongoose

Connecting to a local Mo

Blogs

Book Recommendations