Express + DB
- Node.js course
- Advanced
- Lesson 80/83
- 6 min
Set up the Express API and database layer.
Express + DB
In this lesson we add a database connection to the design skeleton. We will define a simple db object and connect it to an Express route. In a real project this would be an ORM or driver.
Example: const db = { ready: true }; app.get("/db", (req, res) => res.json({ db: db.ready }));. This is a simple mock database connection. In production db becomes a real database driver (MongoDB, PostgreSQL). The skeleton's goal is to show how a database attaches to the app. Express routes access the database through req and res. Database code is called inside route handlers.
Connecting the database to a route
The database is used inside Express routes. A /db route returns the database state as JSON. This pattern is used in real apps to query data.
Example: app.get("/db", (req, res) => { const result = db.query("SELECT * FROM users"); res.json({ data: result }); });. Here db.query sends a query to the database; the result is returned as JSON. In production the query is asynchronous: const result = await db.query(...). Express route handlers can be async. The database connection is usually set up at app startup and shared by all routes. This improves performance.
Practice Add the DB connection
Add const db = { ready: true } and app.get("/db", (req, res) => res.json({ db: db.ready })) to the skeleton below. Print "DB ready" with console.log.
Starter code
const express = require("express");
const app = express();
app.get("/", (req, res) => res.json({ status: "ok" }));
// add db here
// write here
// Print "DB ready"
// write hereSample solution
const express = require("express");
const app = express();
app.get("/", (req, res) => res.json({ status: "ok" }));
const db = { ready: true };
app.get("/db", (req, res) => res.json({ db: db.ready }));
console.log("DB ready");Expected output
DB ready
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the db object line
const db = { ____: true };
const db = { ready: true };
Explanation: db.ready gives the database state.
2 Match each piece to its role
| Term | Meaning |
|---|---|
express |
API framework |
db |
Database |
app.get |
Defines a route |
res.json |
JSON response |
3 How is the database connected to a route?
app.get("/db", (req, res) => res.json(...))- With app.listen
- By using db inside the route handler Correct answer
- With require
- With console.log
Explanation: The database is used inside the route handler.