HelloUniversity Icon HelloUniversity

Introduction to Office Suites

Introduction to Office Suites

Node.js x MongoDB Integration: Where Backend Meets Database

“Data is the new oil, and the ability to work with it efficiently decides the strength of any modern application.” A 2023 Stack Overflow survey revealed that over 46% of developers use Node.js regularly. Pairing it with MongoDB — a database built for flexibility and scale — is not just popular, it’s practical.


This lesson walks you through Node.js x MongoDB integration from setup to deployment. You won’t just see concepts in theory. You’ll create routes, connect to MongoDB Atlas, perform CRUD operations, and even push your project live on Render.


If you’ve worked with Node.js before but never connected it to a real database, this tutorial is your gateway. If you’re already comfortable with JavaScript, you’ll find the steps clear and actionable. And if you’re preparing for real-world projects, this will give you hands-on experience that recruiters actually value.


Ready to roll up your sleeves? Let’s break down each part of Node.js and MongoDB integration — from setting up your environment, to building a working CRUD app, to publishing it online.


Part 1: Setup

Before diving into Node.js and MongoDB integration, you need a clean project environment. By the end of this step, you’ll have your dependencies installed, folder structure ready, and MongoDB connection string secured in a .env file.


Step 1: Create a New Project Folder

mkdir ws2-ecommerce-project
cd ws2-ecommerce-project
        

Step 2: Initialize Node.js Project

Generate a package.json file to track your dependencies and scripts:

npm init -y
        

Step 3: Install Dependencies

You’ll use several packages for Node.js MongoDB integration:

  • express → for handling routes and HTTP requests
  • mongodb → for connecting to MongoDB Atlas
  • dotenv → for storing sensitive credentials like database URI
  • ejs → as the template engine for dynamic HTML rendering
  • body-parser → for reading form submissions

npm install express mongodb dotenv ejs body-parser
        

Step 4: Create Folder Structure

Keep your project clean and organized:

mkdir routes views
        

Your structure should look like this:

ws2-ecommerce-project/
│── node_modules/
│── package.json
│── package-lock.json
│── server.js       
        

Step 5: Set Up Environment File

MongoDB credentials should never be hardcoded. Store them securely in a .env file:

MONGO_URI='mongodb+srv://<username>:<password>@cluster0.mongodb.net/'
        

Replace <username> and <password> with your MongoDB Atlas credentials. This ensures your connection string is safe and easy to update later.


✅ Checkpoint: At this stage, your Node.js project has all dependencies installed, folders organized, and the database connection string stored securely in .env.


Part 2: Server and Database Connection

With your project setup complete, it’s time to connect Node.js to MongoDB Atlas. By the end of this part, you’ll have an Express server running locally and a verified connection to your MongoDB database.


Step 1: Create server.js

This file is the entry point of your app. It loads dependencies, connects to MongoDB, and starts the server:

// server.js
const express = require('express');
const bodyParser = require('body-parser');
const { MongoClient } = require('mongodb');
require('dotenv').config();

const app = express();
const port = 3000;

// Middleware
app.use(bodyParser.urlencoded({ extended: true }));
app.set('view engine', 'ejs');

// MongoDB Setup
const uri = process.env.MONGO_URI;
const client = new MongoClient(uri);

async function main() {
    try {
        await client.connect();
        console.log("Connected to MongoDB Atlas");

        // Select database
        const database = client.db("ecommerceDB");

        // Temporary test route
        app.get('/', (req, res) => {
            res.send("Hello, MongoDB is connected!");
        });

        // Start server
        app.listen(port, () => {
            console.log(`Server running at http://localhost:${port}`);
        });

    } catch (err) {
        console.error("MongoDB connection failed", err);
    }
}

main();
        

Step 2: Run the Server

node server.js
        

If everything is set up correctly, your terminal will display:

Connected to MongoDB Atlas
Server running at http://localhost:3000
        

Step 3: Verify in Browser

Open http://localhost:3000. You should see the message: Hello, MongoDB is connected!


Step 4: What Just Happened

  • Express is serving routes at localhost:3000.
  • MongoClient from the mongodb package established a connection to MongoDB Atlas.
  • dotenv pulled the MONGO_URI from your .env file.
  • client.db("ecommerceDB") selected a database (it will be auto-created if it doesn’t exist).

✅ Checkpoint: Your server is live on http://localhost:3000 and successfully connected to MongoDB Atlas.


Part 3: Routing Setup

Right now, your server works, but everything is inside server.js. To make the project scalable, let’s separate routing into its own files and start using EJS templates.


Step 1: Create a Route File

Inside the routes/ folder, create index.js:

// routes/index.js
const express = require('express');
const router = express.Router();

// Home route
router.get('/', (req, res) => {
    res.render('index', { 
        title: "Home Page", 
        message: "Hello, MongoDB is connected!" 
    });
});

module.exports = router;
        

Step 2: Update server.js to Use Routes

Replace your inline app.get() with the route file:

// server.js (excerpt)
const indexRoute = require('./routes/index');
app.use('/', indexRoute);
        

Step 3: Create an EJS View

Inside the views/ folder, create index.ejs:



    <%= title %>

    

<%= message %>

Welcome to your WS2 E-commerce Project!


Step 4: Run and Verify

Restart the server:

node server.js
        

Open http://localhost:3000. You should see:

  • Page title: Home Page
  • Heading: Hello, MongoDB is connected!
  • A welcome message below

Step 5: What Just Happened

  • Your app now follows a cleaner structure by keeping routes in a separate folder.
  • The homepage is rendered with EJS instead of plain text.
  • Dynamic data (title and message) is passed from the route to the template.

✅ Checkpoint: Your app now uses routes and views. The project structure is ready for forms and full CRUD operations.



quiz Mandatory Assessment

All students must complete the assessment for this lesson. Your submission is required for course completion.

" target="_blank" class="inline-flex items-center px-5 py-3 bg-red-600 text-white rounded-lg font-semibold hover:bg-green-700 transition-colors text-lg shadow"> assignment_turned_in Take the Node.js & MVC Assessment

warning Don’t miss this! Assessment link is required for all students.


Expand Your Knowledge

Dive deeper into technology and productivity with these related articles:

We'd Like to Hear Your Feedback

Comments

No comments yet. Be the first to share your thoughts!