Wiring MongoDB into Express

An Express API connects to MongoDB once when the server starts, hands the database to createApp(db), answers 404 when the repository finds no workout, lets a failed database call reach the error-handling middleware, and closes the connection when Ctrl+C stops it.

Journeyman · Node.js · MongoDB · REST API · Updated

By

After this lesson you can

  • Connect to MongoDB once when the server starts, hand the database to the app with createApp(db), and close the client when Ctrl+C stops it
  • Answer 404 for a missing workout or an id that isn't one, and let database errors reach the error-handling middleware

Key takeaways

  • Connect once, before the server listens. The client keeps a pool of open connections, and every request shares it.
  • app.js exports createApp(db), which builds the app around the database it's given, so server.js can hand it your MongoDB and a test can hand it a throwaway one.
  • A missing workout and text that isn't an id both come back from the repository as null, and the route answers 404 for either.
  • Express 5 passes a failed database call in an async route to the error-handling middleware, which logs it and answers 500.
  • Ctrl+C sends the SIGINT signal. A process.on("SIGINT") handler stops the server, then closes the client.

A script connects, does its work and ends. An API runs for days, takes requests from many people at once, and has to say something sensible when a workout is missing, or when the database itself is. This lesson puts Rep Counter's repository behind Express routes, the shape of every Node API with a database you'll work on.

Connect once, when the server starts

A first try opens the connection inside the route, with new MongoClient, and closes it again before answering. Every request then opens a new line to MongoDB and hangs up, which is slow, and one forgotten close() leaves connections piling up.

A taxi stand works better: a few cars wait there, each rider takes one, and the car comes back for the next rider. A MongoClient keeps a small set of open connections ready in the same way, called a connection pool, and every request borrows one. So the API makes one client, in server.js, before it takes a single request:

import { MongoClient } from "mongodb";
import { createApp } from "./app.js";

const client = new MongoClient(process.env.MONGODB_URI);
await client.connect();
const app = createApp(client.db("rep_counter"));

const server = app.listen(3100, () => {
  console.log("Rep Counter is listening on http://localhost:3100");
});

process.on("SIGINT", async () => {
  server.close();
  await client.close();
  console.log("Stopped the server and closed the database connection.");
});

await client.connect() checks the address before the server starts. If MongoDB isn't running, the server never starts: after about 30 seconds Node stops with MongoServerSelectionError and ECONNREFUSED, as in Connecting from Node and Saving Documents. That's better than an API that starts and then fails its first request.

Handing the database to the app: createApp(db)

In earlier chapters, app.js exported the app itself. This app needs a database, and which one depends on who's asking: server.js has your MongoDB, and a test wants a throwaway one. So app.js exports a function that builds the app around the database it's given. Handing code what it needs, instead of letting it reach out and find it, is called dependency injection:

import express from "express";
import { STATUS_CODES } from "node:http";
import { createWorkoutsRepository } from "./workoutsRepository.js";

function sendProblem(res, status, detail) {
  res.status(status).json({ status, title: STATUS_CODES[status], detail });
}

export function createApp(db) {
  const workouts = createWorkoutsRepository(db);
  const app = express();
  app.use(express.json());

  app.get("/workouts/:id", async (req, res) => {
    const workout = await workouts.get(req.params.id);
    if (workout === null) {
      sendProblem(res, 404, `There's no workout ${req.params.id}.`);
      return;
    }
    res.json(workout);
  });

  app.use((err, req, res, next) => {
    console.error(err);
    sendProblem(res, 500, "Something went wrong on our side.");
  });

  return app;
}

sendProblem is the course's one error shape, from Error Handling and Consistent Error Responses.

Bad and missing ids answer 404

The first try's route, which called findOne itself, got two things wrong. Asked for an id with no workout, it answered 200 with the body null. Asked for /workouts/not-an-id, new ObjectId threw, the terminal logged BSONError: input must be a 24 character hex string, 12 byte Uint8Array, or an integer, and the caller got a 500: the server's fault, for the caller's typo.

With the repository, both come back as null, and the route turns null into a 404. Start the server with node --env-file=.env server.js and send three requests:

GET /workouts/6afc94fb212284a11d88b5de
HTTP/1.1 200 OK
{"id":"6afc94fb212284a11d88b5de","member":"Dana","date":"2026-11-16","sets":[{"exercise":"squat","reps":8,"weight":135}]}

GET /workouts/6740a1000000000000000099
HTTP/1.1 404 Not Found
{"status":404,"title":"Not Found","detail":"There's no workout 6740a1000000000000000099."}

GET /workouts/not-an-id
HTTP/1.1 404 Not Found
{"status":404,"title":"Not Found","detail":"There's no workout not-an-id."}

When the database fails

If MongoDB stops while the API is running, the next findOne rejects with an error, a MongoNetworkError here. Express 5 passes an error from an async route to the error-handling middleware, which logs it in the terminal and gives the caller one calm sentence:

HTTP/1.1 500 Internal Server Error
{"status":500,"title":"Internal Server Error","detail":"Something went wrong on our side."}

No try/catch in the route: the middleware handles every route's database errors in one place.

Closing the connection on Ctrl+C

Pressing Ctrl+C sends the program a signal, a short message from the operating system, named SIGINT (read "sig-int", the interrupt signal). With no handler, Node stops at once. process.on("SIGINT", …) runs your function instead: server.close() stops taking new requests, client.close() hands the pooled connections back to MongoDB, and Node ends once both are done. Press Ctrl+C in the server's terminal:

Rep Counter is listening on http://localhost:3100
Stopped the server and closed the database connection.

Check yourself

2 questions to try on the lesson page.

So what

One client for the whole API, one function that builds the app around it, and every database problem turned into a status code a caller can act on: that's the wiring underneath every Node API with a database.

Key terms

Related