Skip to main content

Command Palette

Search for a command to run...

Node.js and MongoDB Tutorial

Updated
Node.js and MongoDB Tutorial
Y

Tech Lead & Architect | 13+ Years in Cloud, Backend, and AI - Experienced software engineer with expertise in Java, Spring Boot, Microservices, Angular, React, Kafka, DevOps, Python, PySpark, Databricks, and Generative AI. Certified in TOGAF, AWS, and Google Cloud. Passionate about building scalable, secure, and high-performance systems. Enthusiast in Data Engineering & Agentic AI. Author of 1,200+ technical articles sharing insights across diverse tech stacks.

Date: 2021-07-20

This article explains how to build a simple Node.js application that interacts with a MongoDB database to perform Create, Read, Update, and Delete (CRUD) operations. We'll cover setting up the necessary components, defining the data model, handling HTTP requests, and finally running the application.

First, we need to understand the key technologies involved. Node.js is a JavaScript runtime environment that allows you to run JavaScript code outside of a web browser, typically for server-side applications. This enables the creation of dynamic web applications and services. MongoDB is a NoSQL database that stores data in flexible, JSON-like documents. This contrasts with traditional relational databases which organize data into tables with rows and columns. MongoDB's flexibility makes it well-suited for applications needing to handle rapidly evolving data structures.

Before starting the application development, we need to set up the environment. This begins with installing Node.js. The installation process involves downloading an installer from the official Node.js website and running it. The installer often includes npm (Node Package Manager), a tool for managing project dependencies. After installation, verifying the Node.js and npm versions in the command prompt confirms successful installation.

Next, we need a MongoDB database. For simplicity, we'll use Docker, a platform for containerizing applications. Docker allows us to easily set up and manage the MongoDB database within a self-contained environment. A Docker configuration file (often a YAML file) specifies the database setup, including creating an initial database—in this case, a database named "employeedb". Executing commands in the command line interface via Docker allows us to start and stop the database container. Monitoring container statuses using Docker commands ensures the database is running correctly.

Now, we can start building our Node.js application. We choose a project directory and initialize a new Node.js project using the npm init command. This creates a package.json file, a metadata file for the project that lists project dependencies, scripts, version number, and other relevant information. We then add the necessary project dependencies to this package.json file. These dependencies are packages providing functionalities that are not core to Node.js, such as tools for connecting to MongoDB and creating web servers. Using the npm install command downloads and installs these dependencies into a node_modules directory within the project.

The application interacts with MongoDB through a data model, often defined using Mongoose, an Object Data Modeling (ODM) library for MongoDB and Node.js. Mongoose provides a way to define schemas—structures that represent the data—and to interact with the database using JavaScript objects. We create a folder to hold our models and then, within that folder, an employee.js file defines the employee model. This model defines the structure of the data that represents an employee record (e.g., name, ID, department, etc.). The model will map to a collection in the MongoDB database.

To handle incoming HTTP requests, we use a web framework like Express.js. Express.js simplifies creating web servers and defining routes for handling different HTTP requests (GET, POST, PUT, DELETE). We create a routes directory, and within it, an employee.js file. This file defines routes for handling employee-related requests. For example, a GET request might retrieve a list of all employees, a POST request might create a new employee record, a PUT request might update an existing record, and a DELETE request might remove a record. Each route specifies the HTTP method and the URL path, along with the function to be executed when a request matches.

The main application file, typically index.js, sets up the Express.js server, connects to the MongoDB database using Mongoose, registers the routes defined in employee.js, and starts listening on a specified port, usually port 3000. This file acts as the entry point of our application, pulling together all the other parts. Starting the application using the command node index.js in the project's directory starts the server and makes the application accessible. Tools like Postman can then be used to test the application's endpoints, sending various HTTP requests to verify functionality.

This application demonstrates the fundamental principles of building RESTful APIs with Node.js and MongoDB. RESTful APIs adhere to architectural constraints to ensure consistency and interoperability, enabling different systems to easily communicate and share data. The application uses standard HTTP methods (GET, POST, PUT, DELETE) and clearly defined endpoints to manage employee data, making it a simple yet effective example of how these technologies can work together to build scalable web applications. The development process highlights the typical structure of a Node.js project, including the use of a package manager, a data model, a routing mechanism, and the essential components involved in connecting to and interacting with a NoSQL database. This approach, using a well-defined structure and established libraries like Express.js and Mongoose, promotes code readability, maintainability, and scalability.

Read more

More from this blog

The Engineering Orbit

1174 posts

The Engineering Orbit shares expert insights, tutorials, and articles on the latest in engineering and tech to empower professionals and enthusiasts in their journey towards innovation.