Working with Databases in JavaScript: PostgreSQL and MongoDB on Node.js

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

Working with Databases in JavaScript: PostgreSQL and MongoDB on Node.js



Modern web development in JavaScript is unthinkable without effective data management. Node.js, as a server platform, provides powerful tools for interacting with various database management systems (DBMS). In this article, we will take a detailed look at working with two popular solutions — relational PostgreSQL and document-oriented MongoDB. You will learn how to connect to these databases, perform CRUD operations (create, read, update, delete), and make an informed choice between them.



The material will be useful both for beginner developers who are just learning backend development in JavaScript, and for experienced specialists who want to systematize their knowledge. All code examples are written for the Node.js runtime environment.



Setting up the Environment and Installing Drivers



Before starting work, you need to install the appropriate packages via npm. For PostgreSQL, the pg driver is used, and for MongoDB, the official mongodb driver or the popular ODM library mongoose is used.



Create a new project and install the dependencies:



mkdir db-example && cd db-examplenpm init -ynpm install pg mongoose


Now your environment is ready for experiments. Make sure the corresponding database servers are running on your machine (PostgreSQL on port 5432 and MongoDB on port 27017).



1. Working with PostgreSQL via the pg Driver



PostgreSQL is a powerful relational DBMS with SQL support. To interact with it in Node.js, the pg package is used, which provides both a connection pool and an individual client.



Let's look at a basic example of connecting and executing queries:



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

// Configuring the connection poolconst pool = new Pool({ user: 'postgres', host: 'localhost', database: 'testdb', password: 'your_password', port: 5432,});

// Async function for working with the databaseasync function runPostgresExample() { try { // Creating a table await pool.query(` CREATE TABLE IF NOT EXISTS users ( id SERIAL PRIMARY KEY, name VARCHAR(100) NOT NULL, email VARCHAR(100) UNIQUE NOT NULL, age INTEGER ); `);

// INSERT — adding data const insertResult = await pool.query( 'INSERT INTO users (name, email, age) VALUES ($1, $2, $3) RETURNING *', ['Ivan Petrov', 'ivan@example.com', 30] ); console.log('User added:', insertResult.rows[0]);

// SELECT — reading data const selectResult = await pool.query('SELECT * FROM users'); console.log('All users:', selectResult.rows);

// UPDATE — updating data await pool.query( 'UPDATE users SET age = $1 WHERE name = $2', [31, 'Ivan Petrov'] ); console.log('Age updated');

// DELETE — deleting data await pool.query('DELETE FROM users WHERE name = $1', ['Ivan Petrov']); console.log('User deleted'); } catch (err) { console.error('PostgreSQL error:', err.message); } finally { await pool.end(); }}

runPostgresExample();


Note the use of parameterized queries with placeholders $1, $2, etc. This protects against SQL injection and is a best practice. A connection pool is recommended for production environments as it manages connections efficiently.



2. Working with MongoDB via Mongoose



MongoDB is a NoSQL database that stores data in a JSON-like format (BSON). Mongoose provides a convenient abstraction with schemas, validation, and methods for working with collections.



Example of connecting and performing CRUD operations with Mongoose:



const mongoose = require('mongoose');

// Defining the user schema

Blogs

Book Recommendations