Database Integration

Database integration is a fundamental aspect of backend development, enabling applications to store, retrieve, update, and delete data efficiently. This chapter will explore how to integrate databases with Node.js, covering both SQL and NoSQL databases. We will start with basic concepts and move towards advanced topics, including practical examples and detailed explanations.

Databases

Databases are structured collections of data that allow efficient storage, retrieval, and management of information. They are essential for most web applications, enabling dynamic content and data persistence.

Types of Databases

SQL Databases

SQL (Structured Query Language) databases are relational databases that store data in tables with predefined schemas. Common SQL databases include MySQL, PostgreSQL, and SQLite. SQL databases are known for their ACID (Atomicity, Consistency, Isolation, Durability) properties, which ensure reliable transactions.

NoSQL Databases

NoSQL databases are non-relational databases that store data in various formats such as documents, key-value pairs, graphs, and wide-column stores. Examples include MongoDB, Cassandra, and Redis. NoSQL databases are designed for scalability and flexibility, making them suitable for large-scale, distributed applications.

Setting Up the Environment

Before integrating databases with Node.js, ensure you have the following installed:

  • Node.js and npm
  • A database server (e.g., MySQL, PostgreSQL, MongoDB)

Create a new Node.js project:

				
					mkdir db-integration
cd db-integration
npm init -y
npm install express body-parser

				
			

Integrating SQL Databases with Node.js

Using MySQL

1.Install MySQL and MySQL Client Library:

				
					npm install mysql2

				
			

2.Create a MySQL Connection:

				
					// db/mysql.js
const mysql = require('mysql2');

const connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: 'password',
  database: 'testdb'
});

connection.connect((err) => {
  if (err) throw err;
  console.log('Connected to MySQL database!');
});

module.exports = connection;

				
			

3.Performing CRUD Operations:

				
					// app.js
const express = require('express');
const bodyParser = require('body-parser');
const connection = require('./db/mysql');

const app = express();
app.use(bodyParser.json());

// Create
app.post('/users', (req, res) => {
  const { name, email } = req.body;
  const sql = 'INSERT INTO users (name, email) VALUES (?, ?)';
  connection.query(sql, [name, email], (err, result) => {
    if (err) throw err;
    res.status(201).json({ id: result.insertId, name, email });
  });
});

// Read
app.get('/users', (req, res) => {
  const sql = 'SELECT * FROM users';
  connection.query(sql, (err, results) => {
    if (err) throw err;
    res.status(200).json(results);
  });
});

// Update
app.put('/users/:id', (req, res) => {
  const { id } = req.params;
  const { name, email } = req.body;
  const sql = 'UPDATE users SET name = ?, email = ? WHERE id = ?';
  connection.query(sql, [name, email, id], (err) => {
    if (err) throw err;
    res.status(200).json({ message: 'User updated successfully' });
  });
});

// Delete
app.delete('/users/:id', (req, res) => {
  const { id } = req.params;
  const sql = 'DELETE FROM users WHERE id = ?';
  connection.query(sql, [id], (err) => {
    if (err) throw err;
    res.status(200).json({ message: 'User deleted successfully' });
  });
});

app.listen(3000, () => {
  console.log('Server is running on http://localhost:3000');
});

				
			

Using PostgreSQL

1.Install PostgreSQL and Client Library:

				
					npm install pg

				
			

2.Create a PostgreSQL Connection:

				
					// db/postgres.js
const { Pool } = require('pg');

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

module.exports = pool;

				
			

3.Performing CRUD Operations:

				
					// app.js
const express = require('express');
const bodyParser = require('body-parser');
const pool = require('./db/postgres');

const app = express();
app.use(bodyParser.json());

// Create
app.post('/users', async (req, res) => {
  const { name, email } = req.body;
  try {
    const result = await pool.query('INSERT INTO users (name, email) VALUES ($1, $2) RETURNING *', [name, email]);
    res.status(201).json(result.rows[0]);
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
});

// Read
app.get('/users', async (req, res) => {
  try {
    const result = await pool.query('SELECT * FROM users');
    res.status(200).json(result.rows);
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
});

// Update
app.put('/users/:id', async (req, res) => {
  const { id } = req.params;
  const { name, email } = req.body;
  try {
    await pool.query('UPDATE users SET name = $1, email = $2 WHERE id = $3', [name, email, id]);
    res.status(200).json({ message: 'User updated successfully' });
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
});

// Delete
app.delete('/users/:id', async (req, res) => {
  const { id } = req.params;
  try {
    await pool.query('DELETE FROM users WHERE id = $1', [id]);
    res.status(200).json({ message: 'User deleted successfully' });
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
});

app.listen(3000, () => {
  console.log('Server is running on http://localhost:3000');
});

				
			

Integrating NoSQL Databases with Node.js

Using MongoDB

1.Install MongoDB and Mongoose:

				
					npm install mongoose

				
			

2.Create a Mongoose Connection:

				
					// db/mongodb.js
const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost:27017/testdb', {
  useNewUrlParser: true,
  useUnifiedTopology: true
});

const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', () => {
  console.log('Connected to MongoDB!');
});

module.exports = mongoose;

				
			

3.Define a Mongoose Schema and Model:

				
					// models/user.js
const mongoose = require('../db/mongodb');

const userSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true
  },
  email: {
    type: String,
    required: true,
    unique: true
  }
});

module.exports = mongoose.model('User', userSchema);

				
			

3.Performing CRUD Operations:

				
					// app.js
const express = require('express');
const bodyParser = require('body-parser');
const User = require('./models/user');

const app = express();
app.use(bodyParser.json());

// Create
app.post('/users', async (req, res) => {
  const { name, email } = req.body;
  try {
    const user = new User({ name, email });
    await user.save();
    res.status(201).json(user);
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
});

// Read
app.get('/users', async (req, res) => {
  try {
    const users = await User.find();
    res.status(200).json(users);
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
});

// Update
app.put('/users/:id', async (req, res) => {
  const { id } = req.params;
  const { name, email } = req.body;
  try {
    const user = await User.findByIdAndUpdate(id, { name, email }, { new: true });
    res.status(200).json(user);
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
});

// Delete
app.delete('/users/:id', async (req, res) => {
  const { id } = req.params;
  try {
    await User.findByIdAndDelete(id);
    res.status(200).json({ message: 'User deleted successfully' });
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
});

app.listen(3000, () => {
  console.log('Server is running on http://localhost:3000');
});

				
			

Performing CRUD Operations

Create (Insert)

  • SQL: INSERT INTO table_name (column1, column2) VALUES (value1, value2)
  • NoSQL: collection.insertOne({ field1: value1, field2: value2 })

Read(Select)

  • SQL: SELECT * FROM table_name
  • NoSQL: collection.find()

Update

  • SQL: UPDATE table_name SET column1 = value1 WHERE condition
  • NoSQL: collection.updateOne({ filter }, { $set: { field: value } })

Delete

  • SQL: DELETE FROM table_name WHERE condition
  • NoSQL: collection.deleteOne({ filter })

In this chapter, we explored database integration with Node.js, covering both SQL and NoSQL databases. We provided practical examples for MySQL, PostgreSQL, and MongoDB, demonstrating how to perform CRUD operations and query the database. We also touched on advanced topics like transactions and indexing. By following the steps and examples provided, you should be able to integrate databases with your Node.js applications effectively. This comprehensive guide ensures you have all the information needed to manage database operations in your projects.Happy coding !❤️

Table of Contents

Contact here

Copyright © 2025 Diginode

Made with ❤️ in India