Working with Databases in JavaScript (Node.js): PostgreSQL and MongoDB for Beginners
When developing web applications in JavaScript (Node.js), you almost always need to save data: users, orders, articles, or logs. Databases are used for this purpose. In this guide, we will cover two of the most popular systems: the relational PostgreSQL and the document-oriented MongoDB. You will learn how to connect to them from Node.js and perform basic CRUD operations (Create, Read, Update, Delete).
This article is intended for beginner developers familiar with the basics of JavaScript. All code examples can be run in your project.
1. PostgreSQL: Relational Database
PostgreSQL is a powerful SQL database where data is stored in tables with strict field types. To work with it in Node.js, we will use the pg package.
1.1. Installation and Connection
First, install the package via npm:
npm install pgCreate a file db.js and configure the connection to a local database:
const { Pool } = require('pg');
const pool = new Pool({ user: 'postgres', host: 'localhost', database: 'mydb', password: 'password', port: 5432,});
module.exports = pool;1.2. Creating a Table and CRUD Operations
First, let's create a users table with id, name, and email fields. Then we will perform all basic operations.
const pool = require('./db');
// Create tableasync function createTable() { await pool.query(` CREATE TABLE IF NOT EXISTS users ( id SERIAL PRIMARY KEY, name VARCHAR(100) NOT NULL, email VARCHAR(100) UNIQUE NOT NULL ); `); console.log('Table users created');}
// Insert data (CREATE)async function addUser(name, email) { const result = await pool.query( 'INSERT INTO users (name, email) VALUES ($1, $2) RETURNING *', [name, email] ); return result.rows[0];}
// Read data (READ)async function getUsers() { const result = await pool.query('SELECT * FROM users'); return result.rows;}
// Update data (UPDATE)async function updateUser(id, name) { const result = await pool.query( 'UPDATE users SET name = $1 WHERE id = $2 RETURNING *', [name, id] ); return result.rows[0];}
// Delete data (DELETE)async function deleteUser(id) { await pool.query('DELETE FROM users WHERE id = $1', [id]); console.log('User deleted');}
// Usage example(async () => { await createTable(); const newUser = await addUser('Ivan', 'ivan@example.com'); console.log('Added:', newUser);
const users = await getUsers(); console.log('All users:', users);
await updateUser(1, 'Peter'); await deleteUser(2);})();Important: Always use parameterized queries (via $1, $2) to avoid SQL injection.
2. MongoDB: NoSQL Database
MongoDB stores data in JSON-like document format (BSON). For Node.js, the official mongodb driver or the popular mongoose library is used. In this example, we will use the driver.
2.1. Installation and Connection
npm install mongodbConnecting to a local MongoDB (default port 27017):
const { MongoClient } = require('mongodb');
const uri = 'mongodb://localhost:27017';const client = new MongoClient(uri);
async function connect() { await client.connect(); console.log('Connected to MongoDB'); return client.db('mydb'); // database mydb}
module.exports = { connect, client };2.2. CRUD Operations with a Collection
In MongoDB, tables are called collections, and rows are called documents. Let's create a users collection and perform all CRUD operations.