Preparing your workspace
Node.js applications use the MongoDB driver or an ODM to communicate with MongoDB while keeping database access separated from other application layers.
A backend application should manage the MongoDB connection centrally rather than creating a new connection for every request. Database functions can be organized into repositories or data-access modules. Business logic can then call these functions without depending directly on Express request and response objects. The official MongoDB Node.js driver provides direct database access, while ODMs can provide additional modeling abstractions. The choice should match project requirements.
An Express course service can call a course repository to retrieve or update MongoDB documents while keeping database details outside the route controller.
import { MongoClient } from "mongodb";
const client = new MongoClient(process.env.MONGODB_URI);
await client.connect();
const db = client.db("learning_platform");
const courses = db.collection("courses");
const course = await courses.findOne({
slug: "react-fundamentals"
});
console.log(course);The Node.js application connects to MongoDB and retrieves a course document by its slug.