devnotes.

Database Integration in Express

Express handles HTTP; a database handles persistence. Wiring the two together is one of the first things most real Express apps need.

Step 1: Create the Express app

npm init
npm install express
// app.js
const express = require("express");

const app = express();
const PORT = 3900;

app.listen(PORT, (error) => {
    if (!error) {
        console.log(`Server is running and listening on port ${PORT}`);
    } else {
        console.log("Error occurred, server can't start", error);
    }
});

Step 2: Run it once to confirm it works

node app.js

Step 3: Connect a database

There are several common options — MongoDB and MySQL are among the most popular.

MongoDB with Mongoose

npm install mongoose
// app.js
const express = require("express");
const mongoose = require("mongoose");

const app = express();
const PORT = 3900;

mongoose
    .connect("mongodb://localhost:27017/CatalogServiceDB")
    .then(() => {
        app.listen(PORT, () => {
            console.log(`Database connected and server listening on port ${PORT}`);
        });
    })
    .catch((err) => {
        console.log("Could not connect to the database.", err);
    });

Swap the connection string for a MongoDB Atlas URI to use a cloud-hosted database instead of a local instance.

MySQL

npm install mysql
// app.js
const express = require("express");
const mysql = require("mysql");

const app = express();
const PORT = 3900;

const connection = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "yourpassword",
    database: "CatalogServiceDB",
});

connection.connect((error) => {
    if (error) {
        console.log("Could not connect to the database.");
        throw error;
    }

    app.listen(PORT, () => {
        console.log(`Database connected and server listening on port ${PORT}`);
    });
});

A managed MySQL provider works the same way — just swap in the host, user, password, and database values it gives you.

A note on connection order

Starting app.listen() only after the database connects successfully (as shown above) is a common convention — it avoids serving requests before the app can actually talk to its data store. It isn't mandatory, though; some apps start the server immediately and simply return errors on routes that need the database until it's ready.

Database Integration in Express | DevNotes