Integrating a database with an Express.js application is a fundamental skill for any full-stack developer. Databases are essential for storing, retrieving, and managing data in web applications. This chapter will guide you through integrating three popular databases—MongoDB, MySQL, and PostgreSQL—with Express.js. We'll start with the basics, explaining how to connect each database to an Express application, and gradually move on to more advanced topics such as query building, data modeling, and handling complex relationships.
A database is an organized collection of structured information or data, typically stored electronically in a computer system. Databases are managed by a Database Management System (DBMS).
The choice between a relational database (like MySQL or PostgreSQL) and a NoSQL database (like MongoDB) depends on the nature of the data, scalability requirements, and the structure of your application
MongoDB is a NoSQL database that stores data in flexible, JSON-like documents. It is known for its scalability and ease of use, especially in handling unstructured data.
mongod
Mongoose is an ODM (Object Data Modeling) library for MongoDB and Node.js, which provides a schema-based solution to model your data.
npm install mongoose
app.js
const express = require('express');
const mongoose = require('mongoose');
const app = express();
// Connect to MongoDB
mongoose.connect('mongodb://localhost:27017/mydatabase', {
useNewUrlParser: true,
useUnifiedTopology: true
}).then(() => {
console.log('Connected to MongoDB');
}).catch(err => {
console.error('MongoDB connection error:', err);
});
// Middleware
app.use(express.json());
// Sample Schema and Model
const userSchema = new mongoose.Schema({
name: String,
email: String,
age: Number
});
const User = mongoose.model('User', userSchema);
// Routes
app.post('/users', async (req, res) => {
try {
const user = new User(req.body);
await user.save();
res.status(201).json(user);
} catch (err) {
res.status(400).json({ error: err.message });
}
});
app.get('/users', async (req, res) => {
try {
const users = await User.find();
res.json(users);
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// Start Server
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
/users
, a new document is created in the users
collection./users
, all user documents are retrieved from MongoDB.MySQL is a widely-used open-source relational database management system (RDBMS). It is known for its reliability, ease of use, and performance.
mysql -u root -p
mysql2
Packagemysql2
is a Node.js package that allows you to connect to a MySQL database.
npm install mysql2
app.js
const express = require('express');
const mysql = require('mysql2');
const app = express();
// Create MySQL Connection
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'password',
database: 'mydatabase'
});
// Connect to MySQL
connection.connect(err => {
if (err) {
console.error('MySQL connection error:', err);
return;
}
console.log('Connected to MySQL');
});
// Middleware
app.use(express.json());
// Routes
app.post('/users', (req, res) => {
const { name, email, age } = req.body;
const query = 'INSERT INTO users (name, email, age) VALUES (?, ?, ?)';
connection.query(query, [name, email, age], (err, results) => {
if (err) {
res.status(500).json({ error: err.message });
return;
}
res.status(201).json({ id: results.insertId, name, email, age });
});
});
app.get('/users', (req, res) => {
connection.query('SELECT * FROM users', (err, results) => {
if (err) {
res.status(500).json({ error: err.message });
return;
}
res.json(results);
});
});
// Start Server
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
users
table.users
table./users
, a new record is inserted into the users
table./users
, all records from the users
table are retrieved.PostgreSQL is an advanced, open-source relational database that is known for its powerful features and scalability. It supports a wide range of data types and provides robust performance for complex queries.
sudo service postgresql start
pg
Packagepg
is a Node.js package that allows you to connect to a PostgreSQL database.
npm install pg
app.js
const express = require('express');
const { Pool } = require('pg');
const app = express();
// Create PostgreSQL Pool
const pool = new Pool({
user: 'postgres',
host: 'localhost',
database: 'mydatabase',
password: 'password',
port: 5432
});
// Middleware
app.use(express.json());
// Routes
app.post('/users', async (req, res) => {
const { name, email, age } = req.body;
try {
const result = await pool.query(
'INSERT INTO users (name, email, age) VALUES ($1, $2, $3) RETURNING *',
[name, email, age]
);
res.status(201).json(result.rows[0]);
} catch (err) {
res.status(500).json({ error: err.message });
}
});
app.get('/users', async (req, res) => {
try {
const result = await pool.query('SELECT * FROM users');
res.json(result.rows);
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// Start Server
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
users
table and returns the newly created record.users
table./users
, a new record is inserted into the users
table and returned./users
, all records from the users
table are retrieved.
connection.connect(err => {
if (err) {
console.error('MySQL connection error:', err);
// Handle connection error
} else {
console.log('Connected to MySQL');
}
});
Integrating databases with Express.js is an essential skill for building dynamic web applications. Whether you're using MongoDB, MySQL, or PostgreSQL, understanding how to set up, connect, and interact with these databases is crucial. Happy coding !❤️