Connecting to Databases
9 min read
Imagine you are running a busy pizza shop (your Express server). You have customers (client requests) coming in constantly. If you, the chef, forget where you put the cheese every time a new customer walks in, or if you lose the paper where you wrote down their order, you are going to have a bad time. You need a reliable way to remember things—ingredients, recipes, and the cash register—while handling hundreds of orders at once.
In the software world, a database is your shop's filing cabinet and ledger. It ensures you never lose an order, forget a user's profile, or misplace financial records. Let us explore how to connect our Express.js application to a database.
1. Database Paradigms: NoSQL vs SQL Concepts ⚖️
Definition
SQL (Structured Query Language) databases are relational data storage systems that organize data into highly structured tables with strictly defined rows and columns.
NoSQL (Not Only SQL) databases are non-relational data storage systems that store data in flexible formats, most commonly as JSON-like documents.
The Problem
When building an application, you need to store data permanently. However, data comes in different shapes and behaviors. Sometimes your data is highly predictable, interconnected, and requires strict accuracy (like financial ledgers or e-commerce orders). Other times, your data is unpredictable and changes structure frequently (like a user's social media profile that might have varying types of posts, arrays of image links, and custom preferences). If you force highly flexible data into a rigid table structure, you create development bottlenecks. Conversely, if you put strict financial data into a loose, unvalidated document, you risk chaotic, corrupted data.
The Solution
By understanding the difference between SQL and NoSQL, you can tailor your storage mechanism to the exact shape and behavior of your data. SQL enforces strict data integrity and relationships. NoSQL allows for rapid iteration, nested data structures, and high flexibility.
Exploring the Concepts
Fun fact: In the mid-20th century, early "databases" were physical stacks of punch cards. If a developer tripped and dropped a box of punch cards, the database was literally corrupted and had to be manually re-sorted! We have it much easier today with digital tables and documents.
SQL (The Relational Way)
Think of SQL databases like highly organized spreadsheets linked together.
- Tables: Data is stored in tables (e.g., a
Userstable, anOrderstable). - Strict Schema: You must define the exact columns (Name, Age, Email) and their data types before you can insert any data.
- Relations: Tables connect to each other using Foreign Keys. For example, an order in the
Orderstable references theidof a user in theUserstable. - Industry Favorites: PostgreSQL, MySQL, SQLite.
NoSQL (The Document Way)
Think of NoSQL databases like folders containing independent, flexible text files.
- Collections and Documents: Data is grouped into Collections (like a
Userscollection), which contain Documents (individual JSON-like objects representing a single user). - Dynamic Schema: You do not have to define columns upfront. One user document might have a
phoneNumberfield, while another completely lacks it, and the database accepts both without errors. - Embedded Data: Instead of referencing another table, you can embed arrays of data directly inside a document (e.g., putting a list of
recentOrdersdirectly inside the User document). - Industry Favorites: MongoDB, DynamoDB, Redis.
2. Connecting Express to a Database 🔌
Definition
Connecting to a database involves using a software tool—either a database driver, an Object-Relational Mapper (ORM), or an Object-Document Mapper (ODM)—to open a persistent communication channel between your Express.js server and your database server.
The Problem
Databases speak their own complex languages (like raw SQL query strings or specific MongoDB syntax commands). Writing raw query strings directly inside your JavaScript code is difficult to read, highly prone to syntax typos, and extremely vulnerable to security attacks like SQL injection. Furthermore, writing raw database strings means your code editor cannot give you helpful auto-completion or catch type errors.
The Solution
We use tools like Prisma (an ORM for SQL and NoSQL databases) and Mongoose (an ODM specifically for MongoDB). These tools abstract the complex database languages away. They allow you to define your data models using standard JavaScript or TypeScript and interact with the database using simple, secure, auto-completed methods (like User.create()) instead of messy raw strings.
Industry Standard 1: Prisma (For Relational / SQL databases)
Prisma is heavily used in the industry because it provides a type-safe database client and generates models for you.
Installation Setup:
Open your terminal in your project directory and run the latest setup commands from their documentation:
npm install prisma --save-dev
npx prisma init
npm install @prisma/clientWhen you run npx prisma init, Prisma creates a prisma/schema.prisma file and an .env file.
Connecting:
Inside prisma/schema.prisma, you define your database connection and tables.
// prisma/schema.prisma
datasource db {
provider = "postgresql" // or "mysql", "sqlite"
url = env("DATABASE_URL")
}
generator client {
provider = "prisma-client-js"
}
// A simple User table
model User {
id Int @id @default(autoincrement())
name String
email String @unique
}After defining the schema, you apply it to the database using npx prisma db push. Then, you connect it inside your Express application:
// db.js
const { PrismaClient } = require('@prisma/client');
// Initialize Prisma Client
const prisma = new PrismaClient();
module.exports = prisma;Industry Standard 2: Mongoose (For MongoDB / NoSQL databases)
Mongoose is the undisputed champion for connecting Node.js to MongoDB. It adds strict schemas to MongoDB's schema-less nature, giving you the best of both worlds.
Installation Setup:
npm install mongooseConnecting:
// db.js
const mongoose = require('mongoose');
const connectDB = async () => {
try {
// Connect to the MongoDB URI stored in environment variables
await mongoose.connect(process.env.MONGO_URI);
console.log('🍕 MongoDB Connected successfully!');
} catch (error) {
console.error('Database connection failed:', error);
process.exit(1); // Stop the server if the database fails to connect
}
};
module.exports = connectDB;3. Implementing CRUD Operations in Your Controllers 🛠️
Definition
CRUD stands for Create, Read, Update, and Delete. These are the four foundational operations you can perform on persistent database records. Controllers are isolated JavaScript functions that handle incoming HTTP requests and execute these CRUD operations.
The Problem
When a client sends an HTTP request to your Express server (e.g., POST /users), the server needs to know how to translate that HTTP intent into a database action. Without a structured pattern, developers tend to write all their database logic directly inside their route definitions. This creates massive, unreadable files where networking logic, security checks, and database logic are all tangled up.
The Solution
By implementing CRUD operations inside isolated "Controller" functions, you achieve separation of concerns. Returning to our pizza shop flow: The Express Router acts as the waiter taking the order, the Controller is the chef reading the ticket, and the Database is the pantry. The controller takes the request data (req.body), tells the database ORM/ODM what to do, and sends the final response (res.json) back to the client.
CRUD Examples using Mongoose
Let's look at how these four operations are implemented in a user controller. Assume we have a User Mongoose model imported at the top.
const User = require('../models/User'); // Mongoose Model
// 1. CREATE (POST)
const createUser = async (req, res) => {
const { name, email } = req.body;
// Creates and saves a new document to the database
const newUser = await User.create({ name, email });
res.status(201).json(newUser);
};
// 2. READ (GET)
const getUsers = async (req, res) => {
// Finds all documents in the User collection
const users = await User.find();
res.status(200).json(users);
};
// 3. UPDATE (PUT/PATCH)
const updateUser = async (req, res) => {
const { id } = req.params;
const { name } = req.body;
// Finds document by ID, updates it, and returns the new version
const updatedUser = await User.findByIdAndUpdate(
id,
{ name },
{ new: true }
);
res.status(200).json(updatedUser);
};
// 4. DELETE (DELETE)
const deleteUser = async (req, res) => {
const { id } = req.params;
// Finds document by ID and removes it
await User.findByIdAndDelete(id);
res.status(200).json({ message: 'User deleted successfully' });
};
module.exports = { createUser, getUsers, updateUser, deleteUser };(Note: If you were using Prisma, the methods would look very similar, such as prisma.user.create(), prisma.user.findMany(), prisma.user.update(), and prisma.user.delete().)
4. Handling Asynchronous Database Calls Gracefully ⏳
Definition
Asynchronous handling refers to the technique of managing operations that take an unpredictable amount of time to complete (such as querying a database over a network) without pausing or freezing the execution of the rest of your application code.
The Problem
Database operations are not instant; they require network travel time. JavaScript is single-threaded, meaning it only has one "brain" to process tasks. If your Express server stops completely to wait 2 seconds for the database to return User A's profile, it cannot accept incoming requests from User B or User C during those 2 seconds. Furthermore, if the database crashes or the query fails, and you do not anticipate the error, the unhandled rejection will crash your entire Node.js server, terminating the program for everyone.
The Solution
By utilizing JavaScript's async/await syntax paired with try/catch blocks, your server can delegate the waiting task to the background. The server continues accepting new requests while waiting for the database to respond. If the database operation fails, the catch block intercepts the error gracefully, prevents the server from crashing, and allows you to send a polite error response to the client.
Applying try/catch in Controllers
Here is how you handle asynchronous calls securely in an Express controller. We pass any caught errors to Express's next() function, which triggers your application's global error handler.
const getUserById = async (req, res, next) => {
try {
const { id } = req.params;
// The 'await' keyword tells JavaScript to pause THIS function
// and do other server tasks until the database responds.
const user = await User.findById(id);
// If the database returns null (user not found)
if (!user) {
return res.status(404).json({ error: 'User not found' });
}
res.status(200).json(user);
} catch (error) {
// If the database throws an error (e.g., connection lost, invalid ID format)
// We catch it and pass it to next(), preventing a server crash.
console.error("Database query failed:", error.message);
next(error);
}
};Fun fact: If Node.js didn't handle tasks asynchronously via its built-in Event Loop, a single slow database query would literally freeze the webpage for every single person trying to access your application globally!
Further Reading & References 📚
To deepen your understanding and see the official documentation for the tools we used, check out the links below:
Challenge
Challenge: Implement a Full CRUD Controller for a Product API
You are tasked with building the controller logic for a 'Product' resource in an Express.js application that uses Mongoose as its ODM. Your goal is to implement all four CRUD (Create, Read, Update, Delete) operations.
Assume that a Mongoose model named Product has already been defined and is available for use within your controller file.
Requirements:
Create Function (
createProduct):- This function will handle
POSTrequests. - It should extract the product data (e.g.,
name,price,description) from the request body (req.body). - Use the appropriate Mongoose method to create a new product document in the database.
- On success, respond with a
201status code and the newly created product object in JSON format.
- This function will handle
Read Function (
getAllProducts):- This function will handle
GETrequests to fetch all products. - Use the appropriate Mongoose method to retrieve all documents from the
Productcollection. - On success, respond with a
200status code and an array of all product objects in JSON format.
- This function will handle
Update Function (
updateProduct):- This function will handle
PUTrequests to update a specific product. - It should extract the product's unique ID from the request parameters (
req.params). - It should extract the new update data from the request body (
req.body). - Use the Mongoose method that finds a document by its ID and updates it. Ensure the method returns the newly updated document.
- On success, respond with a
200status code and the updated product object in JSON format.
- This function will handle
Delete Function (
deleteProduct):- This function will handle
DELETErequests to remove a specific product. - It should extract the product's unique ID from the request parameters (
req.params). - Use the appropriate Mongoose method to find a document by its ID and remove it from the database.
- On success, respond with a
200status code and a JSON object confirming the deletion (e.g.,{ message: 'Product deleted successfully' }).
- This function will handle
Error Handling Requirement:
- All four controller functions must be asynchronous and use
async/awaitsyntax. - Each function must be wrapped in a
try/catchblock to handle potential database errors gracefully. If an error is caught, the function should respond with a500status code and a JSON object containing an error message.
Expected result
The final code should be a complete JavaScript module that exports four asynchronous controller functions. Each function must correctly implement its specified CRUD operation using appropriate Mongoose methods and include robust try/catch error handling.
Detailed Breakdown of the Expected Solution:
createProduct(req, res):- Must be an
asyncfunction. - Inside a
tryblock, it callsawait Product.create(req.body). - On success, it calls
res.status(201).json(newProduct). - The
catchblock callsres.status(500).json({ error: '...' }).
- Must be an
getAllProducts(req, res):- Must be an
asyncfunction. - Inside a
tryblock, it callsawait Product.find({}). - On success, it calls
res.status(200).json(products). - The
catchblock callsres.status(500).json({ error: '...' }).
- Must be an
updateProduct(req, res):- Must be an
asyncfunction. - It must destructure the product ID from
req.params(e.g.,const { id } = req.params;). - Inside a
tryblock, it callsawait Product.findByIdAndUpdate(id, req.body, { new: true, runValidators: true }). - On success, it calls
res.status(200).json(updatedProduct). - The
catchblock callsres.status(500).json({ error: '...' }).
- Must be an
deleteProduct(req, res):- Must be an
asyncfunction. - It must destructure the product ID from
req.params. - Inside a
tryblock, it callsawait Product.findByIdAndDelete(id). - On success, it calls
res.status(200).json({ message: 'Product deleted successfully' }). - The
catchblock callsres.status(500).json({ error: '...' }).
- Must be an
Exports:
- The file must end with
module.exportscontaining all four function names.
- The file must end with