Loading

Quipoin Menu

Learn • Practice • Grow

express-js / Express.js Database Basics
tutorial

Express.js Database Basics

Most real-world applications need to store data permanently – user accounts, products, orders, blog posts. This is where **databases** come in. In this chapter, we'll learn the basics of integrating databases with Express.js applications.

What is a Database?

A database is an organized collection of data stored electronically. Think of it as a digital filing cabinet where you can store, retrieve, and manipulate data efficiently.

If Express is your restaurant's kitchen, the database is your cold storage and pantry – it's where all the ingredients (data) are kept until needed.

Types of Databases

TypeDescriptionExamples
Relational (SQL)Data organized in tables with rows and columns. Uses structured query language (SQL).MySQL, PostgreSQL, SQLite
Non-relational (NoSQL)Flexible data models – documents, key-value pairs, graphs.MongoDB, Firebase, Redis

How Express Communicates with Databases

Express itself doesn't talk directly to databases. Instead, we use **database drivers** or **ODM/ORM libraries**:
  • Database Driver: Low-level library that speaks the database's protocol (e.g., `mysql2`, `pg` for PostgreSQL).
  • ODM (Object Document Mapper): For NoSQL databases – maps documents to JavaScript objects (e.g., Mongoose for MongoDB).
  • ORM (Object Relational Mapper): For SQL databases – maps tables to JavaScript objects (e.g., Sequelize, TypeORM).

Basic Database Connection Pattern

Regardless of which database you choose, the pattern is similar:
  1. Install the database driver/ORM.
  2. Create a connection to the database.
  3. Use the connection in your routes to query data.
  4. Close the connection when your app shuts down.

Environment Variables for Database Credentials

Never hardcode database credentials! Use environment variables:
<!-- .env file -->
DB_HOST=localhost
DB_USER=root
DB_PASSWORD=secret
DB_NAME=mydb

<!-- In your app -->
require('dotenv').config();

const dbConfig = {
  host: process.env.DB_HOST,
  user: process.env.DB_USER,
  password: process.env.DB_PASSWORD,
  database: process.env.DB_NAME
};

Two Minute Drill

  • Databases store persistent data for your Express applications.
  • Two main types: SQL (relational) and NoSQL (non-relational).
  • Express uses drivers/ORMs to communicate with databases.
  • Always store database credentials in environment variables.
  • Choose the right database based on your data structure and application needs.

Need more clarification?

Drop us an email at career@quipoinfotech.com