DocsHub
Back-EndSetup

MongoDB Connection

Connecting an Express backend to MongoDB using Mongoose — with proper error handling and connection events.

MongoDB Connection

This replaces the placeholder db.js from the previous file with a real MongoDB connection using Mongoose — including error handling and connection event logging.


db.js — Full Connection Setup

// src/config/db.js
import mongoose from "mongoose";

const connectDB = async () => {
  try {
    // Step 1 — connect using the URI from environment variables
    const conn = await mongoose.connect(process.env.MONGO_URI);

    console.log(`MongoDB connected: ${conn.connection.host}`);

    return conn;
  } catch (error) {
    // Step 2 — if connection fails, throw so server.js can catch it
    // and exit the process instead of running with no database
    throw new Error(`MongoDB connection failed: ${error.message}`);
  }
};

// Step 3 — listen for connection events after the initial connect
// useful for catching disconnects that happen later, not just on startup
mongoose.connection.on("disconnected", () => {
  console.log("MongoDB disconnected");
});

mongoose.connection.on("reconnected", () => {
  console.log("MongoDB reconnected");
});

mongoose.connection.on("error", (error) => {
  console.error("MongoDB connection error:", error.message);
});

export default connectDB;

How It Connects With server.js

yes no server.js calls connectDB mongoose.connect with MONGO_URI Connected? Return connection server.js starts app.listen Throw error server.js catches it and exits

server.js from the previous file already handles both outcomes:

connectDB()
  .then(() => {
    app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
  })
  .catch((error) => {
    console.error("Failed to connect to database:", error.message);
    process.exit(1);
  });

Getting a MONGO_URI — Local vs Atlas

Local MongoDB

# .env
MONGO_URI=mongodb://localhost:27017/myapp

Requires MongoDB installed and running locally — mongod running in the background.

# .env
MONGO_URI=mongodb+srv://username:password@cluster0.mongodb.net/myapp?retryWrites=true&w=majority
  1. Create a free cluster at mongodb.com/atlas
  2. Create a database user with a username and password
  3. Add your IP to the network access list (or 0.0.0.0/0 for development)
  4. Copy the connection string and replace <password> with your actual password

Never commit a real MONGO_URI with credentials to git. It always lives in .env, which is in .gitignore.


Testing the Connection

npm run dev
# expected output on success
MongoDB connected: cluster0-shard-00-01.mongodb.net
Server running on port 5000
# expected output on failure (e.g. wrong password)
Failed to connect to database: MongoDB connection failed: bad auth : authentication failed

Summary

  • connectDB() uses mongoose.connect(process.env.MONGO_URI) wrapped in try/catch
  • Connection events — disconnected, reconnected, error — are logged for visibility after the initial connection
  • Local development can use a local MongoDB instance or MongoDB Atlas — Atlas is recommended even for development
  • Failed connections throw an error that server.js catches, logging it and exiting the process rather than running with no database
  • Real credentials always go in .env, never committed to git

On this page