Introduction to Working with Databases in JavaScript (Node.js)
\nModern web development rarely goes without interacting with databases. Whether it's storing users, blog posts, or data for analytics — the ability to work with databases is a mandatory skill for every developer. In this article, we will look at two of the most popular types of databases: the relational PostgreSQL and the document-oriented MongoDB. We will write simple examples in JavaScript (Node.js) that will help you get started with both systems.
\n\n1. Environment Setup and Installing Dependencies
\nBefore writing code, you need to install drivers for Node.js to interact with the chosen databases. To do this, create a new project and install the packages via npm.
\n\nInstalling Drivers
\n- \n
- pg — a popular client for PostgreSQL. \n
- mongoose — an ODM (Object Document Mapper) for MongoDB that simplifies working with collections. \n
mkdir db-example && cd db-example\nnpm init -y\nnpm install pg mongoose\n\nNow your environment is ready for experiments.
\n\n2. Working with PostgreSQL from Node.js
\nPostgreSQL is a powerful relational database that uses SQL for queries. We will connect to a local server, create a table, and perform basic CRUD (Create, Read, Update, Delete) operations.
\n\nConnecting to the Database
\nCreate a file postgres.js and add the following code for connection:
const { Pool } = require('pg');\n\nconst pool = new Pool({\n user: 'your_username',\n host: 'localhost',\n database: 'testdb',\n password: 'your_password',\n port: 5432,\n});\n\nasync function connect() {\n try {\n const client = await pool.connect();\n console.log('Connected to PostgreSQL');\n client.release();\n } catch (err) {\n console.error('Connection error:', err);\n }\n}\n\nconnect();\n\nCreating a Table and Inserting Data
\nNow let's add a function to create the users table and insert records:
async function createTable() {\n const query = `\n CREATE TABLE IF NOT EXISTS users (\n id SERIAL PRIMARY KEY,\n name VARCHAR(100) NOT NULL,\n email VARCHAR(100) UNIQUE NOT NULL\n );\n `;\n await pool.query(query);\n console.log('Table users created');\n}\n\nasync function insertUser(name, email) {\n const query = 'INSERT INTO users (name, email) VALUES ($1, $2) RETURNING *';\n const values = [name, email];\n const res = await pool.query(query, values);\n console.log('User added:', res.rows[0]);\n}\n\n// Example usage\ncreateTable().then(() => insertUser('Ivan', 'ivan@example.com'));\n\nReading and Updating Data
\nLet's get all users and update an email:
\nasync function getUsers() {\n const res = await pool.query('SELECT * FROM users');\n console.log('All users:', res.rows);\n}\n\nasync function updateUserEmail(id, newEmail) {\n const query = 'UPDATE users SET email = $1 WHERE id = $2 RETURNING *';\n const res = await pool.query(query, [newEmail, id]);\n console.log('User updated:', res.rows[0]);\n}\n\ngetUsers().then(() => updateUserEmail(1, 'ivan_new@example.com'));\n\nPostgreSQL is great for projects where data integrity and complex relationships between tables are important.
\n\n3. Working with MongoDB from Node.js
\nMongoDB is a NoSQL database that stores data in a format similar to JSON (BSON). It is flexible and does not require a strict schema. For working with it, we will use Mongoose.
\n\nConnecting to MongoDB
\nCreate a file mongo.js:
const mongoose = require('mongoose');\n\nconst connectDB = async