ExpressJS Database Basics
Imagine you run a library. You have thousands of books, information about members, records of who borrowed what, and due dates. Without a proper system, finding a book or knowing who has it would be chaos. In web applications, databases are that organized system they store, manage, and retrieve data efficiently.
What is a Database?
A database is an organized collection of data that can be easily accessed, managed, and updated. Think of it as a digital filing cabinet where information is stored in a structured way.
Types of Databases
There are two main types of databases commonly used with Express:
- SQL Databases (Relational) Store data in tables with rows and columns. Examples: MySQL, PostgreSQL, SQLite. They use structured query language (SQL) and have predefined schemas.
- NoSQL Databases (Non-relational) Store data in flexible formats like documents, key-value pairs, or graphs. Examples: MongoDB, Firebase, Redis. They are schema-less and great for unstructured data.
Why Do We Need Databases in Web Apps?
- Persistence Data survives server restarts.
- Organization Structured storage makes data easy to find.
- Scalability Handle large amounts of data efficiently.
- Multi-user access Multiple users can access data simultaneously.
- Security Built-in user authentication and authorization.
- Relationships Connect related data (like users to their orders).
How Express Communicates with Databases
Express doesn't talk directly to databases. Instead, we use database drivers or ORMs/ODMs:
- Drivers Low-level libraries that allow Express to connect and send queries to databases. Examples:
mysql2,pg(PostgreSQL),mongodb. - ORMs/ODMs Object Relational Mappers (for SQL) or Object Document Mappers (for NoSQL). They provide a higher-level abstraction, letting you work with database records as JavaScript objects. Examples:
Sequelize(SQL),Mongoose(MongoDB),TypeORM.
Basic Flow: Express + Database
- Client makes a request to an Express route (like GET /users).
- Route handler uses a database driver/ORM to query the database.
- Database returns the requested data.
- Express sends that data back to the client (as JSON, HTML, etc.).
Simple Example (Conceptual)
const express = require('express');
const app = express();
// Assume we have a database connection
const db = require('./database');
app.get('/users', async (req, res) => {
try {
// Query the database
const users = await db.query('SELECT * FROM users');
res.json(users);
} catch (error) {
res.status(500).json({ error: error.message });
}
});Two Minute Drill
- Databases store and organize application data persistently.
- SQL databases (MySQL, PostgreSQL) use tables and structured schemas.
- NoSQL databases (MongoDB) use flexible documents.
- Express uses drivers or ORMs/ODMs to communicate with databases.
- Choose a database based on your data structure and application needs.
Need more clarification?
Drop us an email at career@quipoinfotech.com
