Preparing your workspace
Node.js applications use database drivers or libraries to read and write persistent application data.
A backend application often needs a database for users, courses, orders, progress, and other persistent information. Node.js can work with relational and document databases through drivers and libraries. Good architecture separates database access from request handling and business logic. Database operations should be asynchronous and should handle connection failures and query errors. Connection management also matters because creating unnecessary connections for every request can reduce performance and reliability.
A course API can receive a request, validate the user, call a course service, and then use a database repository to retrieve the course record.
async function getCourse(repository, courseId) {
const course = await repository.findById(courseId);
if (!course) {
throw new Error('Course not found');
}
return course;
}The service returns a course when it exists and throws an error when the course cannot be found.