Setting Up MongoDB Atlas with Node.js, Express, and Mongoose

Omkar KastureOmkar Kasture
5 min read

This guide covers setting up MongoDB Atlas, creating a Node.js project, and integrating Express with Mongoose for backend development. The article provides instructions for initializing a Node.js project, setting up an Express server, and connecting to MongoDB using Mongoose. It also covers environment variable management with dotenv, schema and model creation using Mongoose, structuring Express routes and controllers, and implementing input validation with express-validator.

Express and Mongoose Setup

MongoDB vs. MongoDB Atlas

MongoDB

  • A NoSQL database that stores data in JSON-like documents.

  • Offers flexibility, scalability, and high performance for modern applications.

  • Can be self-hosted on local servers, cloud VMs, or on-premise infrastructure.

MongoDB Atlas

  • A fully managed cloud database service for MongoDB.

  • Provides automated backups, scaling, security, and monitoring.

  • Runs on AWS, Azure, and Google Cloud, reducing operational overhead.


Steps to Set Up MongoDB Atlas

1. Create an Account

2. Create a Cluster

  • Click "Create a New Cluster"

  • Choose a cloud provider (AWS, GCP, or Azure)

  • Select a region and free/shared tier (for free usage)

  • Click "Create Cluster" (Takes a few minutes)

3. Set Up Database Access

  • Go to Database Access → Click "Add New User"

  • Set a username & password (Remember these for later)

  • Choose Role: Atlas Admin

4. Set Network Access

  • Go to Network Access → Click "Add IP Address"

  • Select "Allow Access from Anywhere" (or add your IP)

5. Connect to Your Cluster

  • Click "Connect" on your cluster

  • Choose "Connect Your Application"

  • Copy the connection string (mongodb+srv://...)

  • Use this string in your MongoDB Compass, terminal, or Node.js app


Set Up Express for Backend

1. Initialize a Node.js Project

mkdir Backend
cd Backend
npm init -y

(This creates a package.json file.)

2. Install Express, nodemon, mongoose

npm install express nodemon mongoose

3. Create an index.js File

touch index.js

4. Set Up a Basic Express Server

const express = require("express");
const app = express();

app.get("/", (req, res) => {
  res.send("Hello, Express!");
});

const PORT = 3000;
app.listen(PORT, () => {
  console.log(`Server running on http://localhost:${PORT}`);
});

Different Ways to import packages

1. (CommonJS) const x = require("x");

  • You are working with Node.js (CommonJS).

  • The project does not support ES Modules (e.g., older Node.js versions).

  •   const fs = require("fs");
    

2. ES Modules - Default Export

  • You are using ES Modules (ECMAScript Modules / ESM).

  • "type": "module" is set in package.json.

  • The package exports a default module.

  •   import express from "express";
    

3. ES Modules - Named Export

  • The module exports named exports instead of a default export.

  •   import { Router } from "express";
    

Setup mongoose

Create a db.js File for MongoDB Connection

const mongoose = require("mongoose");

const password = encodeURIComponent("<password>")

//replace DB_URI with your_correct_mongodb_connection_string
const DB_URI = `mongodb+srv://username:${password}@cluster/dbname?authSource=authSource&authMechanism=authMechanism`
//make sure you added database name correctly
const connectDB = async () => {
  try {
    await mongoose.connect(DB_URI);
    console.log("MongoDB Connected!");
  } catch (err) {
    console.error("MongoDB Connection Error:", err);
    process.exit(1); // Exit process with failure
  }
};

module.exports = connectDB;

Ensure any option params are URL encoded.

Use db.js in index.js

const connectDB = require("./db"); // Import the MongoDB connection function
// Connect to MongoDB
connectDB();

Use of .env

A .env (environment variables) file stores configuration settings (like database credentials, API keys) securely so they are not hardcoded in your codebase.

  1. Install dotenv Package

npm install dotenv
  1. Create a .env File

DB_URI=your_correct_mongodb_connection_string
DB_Password=your_password

3. Load .env Variables in db.js

require("dotenv").config(); // Load environment variables

const encodedPassword = encodeURIComponent(process.env.DB_Password); // Encodes special characters
const DB_URI = process.env.DB_URI.replace("<password>", encodedPassword);

mongoose.connect(process.env.MONGO_URI)

Communication with Database

Model and Schema

MongoDB is schema-less, but we can introduce schema in MongoDB using mongoose.

  • Schema: Defines the structure of documents in a collection (like a blueprint).

  • Model: A wrapper around the schema to interact with the actual MongoDB collection (CRUD operations).

Create models/User.js

const mongoose = require("mongoose");

// Define User Schema
const userSchema = new mongoose.Schema({
  name: { type: String, required: true },
  email: { type: String, required: true, unique: true },
  password: { type: String, required: true },
  createdAt: { type: Date, default: Date.now }
});

// Create User Model
const User = mongoose.model("User", userSchema);

module.exports = User;

Now we can import “User” model anywhere to do CRUD operations on user collection.


Structuring Express with Routes & Controllers

Instead of writing everything in index.js, we separate routes and controllers for better organization.

1. Create Controller (controllers/userController.js)

Here we write functions to Handles business logic (CRUD operations)

const User = require("../models/User");

// Create a new user
const createUser = async (req, res) => {
  try {
    const user = new User(req.body);
    await user.save();
    res.status(201).json(user);
  } catch (err) {
    res.status(400).json({ error: err.message });
  }
};

module.exports = { createUser};

2. Create Routes (routes/userRoutes.js)

Here we create APIs

const express = require("express");
const { createUser } = require("../controllers/userController");

const router = express.Router();

router.post("/register", createUser); // Create user

module.exports = router;

3. Use Routes in index.js

require("dotenv").config();
const express = require("express");
const connectDB = require("./config/db");
const userRoutes = require("./routes/userRoutes");

const app = express();
app.use(express.json());

connectDB(); // Connect MongoDB

app.use("/api/users", userRoutes); // Use user routes

app.listen(5000, () => console.log("Server running on port 5000"));

Express Validator

express-validator is a middleware for validating and sanitizing user input in Express applications. It helps prevent common security issues like SQL injection, XSS attacks, and invalid data.

npm install express-validator

Import and Apply Validation in Routes (routes/userRoutes.js)

const express = require("express");
const { check, validationResult } = require("express-validator");
const { createUser } = require("../controllers/userController");

const router = express.Router();

router.post(
  "/register",
  [
    check("name").notEmpty().withMessage("Name is required"),
    check("email").isEmail().withMessage("Invalid email format"),
    check("password").isLength({ min: 8 }).withMessage("Password must be at least 8 characters"),
  ],
  createUser
);

module.exports = router;

Handle Errors in Controller (controllers/userController.js)

const { validationResult } = require("express-validator");
const User = require("../models/User");

const createUser = async (req, res) => {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.status(400).json({ errors: errors.array() }); // Return validation errors
  }

  try {
    const user = new User(req.body);
    await user.save();
    res.status(201).json(user);
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
};

module.exports = { createUser };

0
Subscribe to my newsletter

Read articles from Omkar Kasture directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Omkar Kasture
Omkar Kasture

MERN Stack Developer, Machine learning & Deep Learning