Practical Project — Node.js Application with MongoDB
Let's now look at a practical real-world use case.
We have already set up a basic Node.js application called test-app.
Inside test-app, there is a file called server.js which has a basic backend setup with Express and a Mongoose client.
We have created two routes:
GET /get-users — to fetch all users data from our database.
POST /add-user — to add a new user to our database.
The server is running on port 5050, and this is our basic server setup.
Application Overview
The UI for our test application looks like a basic university website where any student or user can create their account.
Our Node.js application needs to connect with a MongoDB database (college-db).
However, we do not have MongoDB installed on our local system.
Instead, we are going to use MongoDB through Docker containers, and our application will interact with those containers to store and fetch data.
Docker Images Used
For this setup, we are going to make use of two Docker images:
| Docker Image | Purpose |
|---|
mongo | MongoDB database running inside a Docker container |
mongo-express | Web-based UI for MongoDB that allows us to view and manage database data through the browser |
Architecture Overview
+----------------------+
| Node.js App |
| (test-app) |
| Port: 5050 |
+----------+-----------+
|
|
v
+----------------------+
| MongoDB Container |
| (mongo) |
| Database: |
| college-db |
+----------+-----------+
|
|
v
+----------------------+
| Mongo Express UI |
| (mongo-express) |
| Browser Interface |
+----------------------+
Workflow
- A user interacts with the Node.js application.
- The Node.js backend receives the request.
- The backend communicates with the MongoDB container.
- Data is stored in or retrieved from the
college-db database.
- The database contents can also be viewed through the
mongo-express UI in the browser.
Components Summary
| Component | Description |
|---|
| Node.js Application | Handles API requests and business logic |
| Express | Creates backend routes and server |
| Mongoose | Connects Node.js with MongoDB |
MongoDB Container (mongo) | Stores application data |
Mongo Express (mongo-express) | Provides a graphical interface for MongoDB |
| Docker | Runs MongoDB and Mongo Express inside isolated containers |
Routes Implemented
Fetch All Users
Used to retrieve all users from the database.
Add a User
Used to insert a new user into the database.
Key Benefit of Using Docker Here
Instead of installing MongoDB directly on our machine:
- MongoDB runs inside a Docker container.
- The database environment remains isolated.
- Setup becomes faster and more portable.
- Other developers can run the same database setup using Docker.
- The database can be removed and recreated without affecting the host system.
This makes Docker an excellent choice for developing and deploying applications that depend on databases such as MongoDB.