Skip to content
Databases⏱️ 12 min read·

How to Connect MongoDB to a Node.js Application with Mongoose (Handling Retries & Disconnections)

Learn how to connect MongoDB (Local or Atlas) to Node.js using Mongoose. Handle special characters in connection strings, connection pooling, and auto-reconnect listeners.

MN
Manoj NeupaneSoftware Developer & Programming Instructor
#MongoDB#Mongoose#Node.js#Express#Database
🎯 Who This Tutorial Is For

MERN stack developers and Node.js students connecting applications to MongoDB Atlas cloud or local MongoDB instances.

📋 Prerequisites
  • ✓Node.js 18+ installed
  • ✓Mongoose package installed (npm install mongoose)
  • ✓MongoDB Atlas account or local mongod service

🚀 What You Will Learn & Build

  • ▸Writing a robust, modular database connection module
  • ▸Safely escaping special characters in Atlas passwords
  • ▸Handling connection events (connected, error, disconnected)
  • ▸Configuring connection pools and timeouts for production
1

1. The Production-Ready Database Connection Module

Never write your database connection logic directly inside `server.js`. Create a dedicated module:
const mongoose = require('mongoose');

const connectDB = async () => {
  try {
    const conn = await mongoose.connect(process.env.MONGODB_URI, {
      maxPoolSize: 10, // Maintain up to 10 socket connections
      serverSelectionTimeoutMS: 5000, // Timeout after 5s instead of hanging
      socketTimeoutMS: 45000, // Close sockets after 45s of inactivity
    });

    console.log(`✅ MongoDB Connected: ${conn.connection.host}`);
  } catch (error) {
    console.error(`❌ MongoDB connection error: ${error.message}`);
    process.exit(1); // Exit process with failure
  }
};

// Event Listeners for Lifecycle Monitoring
mongoose.connection.on('disconnected', () => {
  console.warn('⚠️ MongoDB disconnected! Attempting reconnect...');
});

mongoose.connection.on('error', (err) => {
  console.error('⚠️ MongoDB runtime error:', err);
});

module.exports = connectDB;
2

2. Handling Special Characters in MongoDB Atlas Passwords

If your MongoDB Atlas password contains special characters like `@`, `#`, `/`, or `:`, the connection string parser fails with: ``` MongoParseError: URI does not have valid format ``` **Solution:** URL-encode the special characters or use encodeURIComponent in JavaScript: - `@` becomes `%40` - `#` becomes `%23` - `/` becomes `%2F`

✨ Expected Output & Verification

Console logs: ✅ MongoDB Connected: cluster0-shard-00-00.mongodb.net Server running on port 5000

🧪 How to Test the Implementation

  1. 1Temporarily disconnect Wi-Fi to test the disconnected event handler
  2. 2Check `http://localhost:5000/api/health` to confirm dbReadyState returns 1 (connected)

⚠️ Common Errors & How to Fix Them

❌MongooseServerSelectionError: connect ECONNREFUSED

Root Cause: IP Address not whitelisted in MongoDB Atlas Network Access.

Fix: In MongoDB Atlas dashboard, go to Network Access and add your current IP or allow 0.0.0.0/0 (for development).

🛡️ Security Considerations & Best Practices

  • !Never push .env files containing MongoDB connection strings with usernames and passwords to GitHub.

❓ Frequently Asked Questions (FAQ)

Yes, MongoDB Atlas provides an M0 Sandbox cluster with 512MB storage and shared RAM for free forever.

📌 Summary of Key Takeaways

  • ✓Modularize connection logic and handle lifecycle events.
  • ✓URL-encode special characters in Atlas passwords.

Official References & Further Reading