Working with Databases in JavaScript: PostgreSQL and MongoDB for Beginners

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 (Node.js)

\n

Modern 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\n

1. Environment Setup and Installing Dependencies

\n

Before 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\n

Installing Drivers

\n
    \n
  • pg — a popular client for PostgreSQL.
  • \n
  • mongoose — an ODM (Object Document Mapper) for MongoDB that simplifies working with collections.
  • \n
\n
mkdir db-example && cd db-example\nnpm init -y\nnpm install pg mongoose
\n\n

Now your environment is ready for experiments.

\n\n

2. Working with PostgreSQL from Node.js

\n

PostgreSQL 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\n

Connecting to the Database

\n

Create a file postgres.js and add the following code for connection:

\n
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\n

Creating a Table and Inserting Data

\n

Now let's add a function to create the users table and insert records:

\n
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\n

Reading and Updating Data

\n

Let's get all users and update an email:

\n
async 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\n

PostgreSQL is great for projects where data integrity and complex relationships between tables are important.

\n\n

3. Working with MongoDB from Node.js

\n

MongoDB 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\n

Connecting to MongoDB

\n

Create a file mongo.js:

\n
const mongoose = require('mongoose');\n\nconst connectDB = async                

Blogs

Book Recommendations