MongoDBMongooseError Fix2026 Updated

Mongoose Connection Error— Fixed [Complete Guide 2026]

Also covers: MongoServerError authentication failed · MongoDB connection refused · ECONNREFUSED 127.0.0.1:27017

January 20268 min readMongoDB · Node.js · All OS

⚡ Identify Your Error in 30 Seconds

The exact error message tells you what is wrong. Check yours below:

ECONNREFUSED 127.0.0.1:27017MongoDB not running locally → Fix 1
MongoServerError: Authentication failedWrong credentials → Fix 3
ServerSelectionTimeoutErrorAtlas IP not whitelisted → Fix 4
Invalid schemeWrong connection string format → Fix 2

Diagnose Your Error Fast

ECONNREFUSED 127.0.0.1:27017

MongoDB is not running on your local machine. Nothing is listening on port 27017.

MongoServerError: Authentication failed

MongoDB rejected your username/password. Wrong credentials or user does not have permission for that database.

MongoServerSelectionError / ServerSelectionTimeoutError

Cannot reach MongoDB at all — either it is not running, IP is blocked by firewall, or Atlas Network Access has not whitelisted your IP.

Invalid scheme, expected connection string to start with mongodb:// or mongodb+srv://

Connection string format is wrong — missing the protocol prefix or using a malformed URI.

1

MongoDB Not Running Locally (ECONNREFUSED)

ECONNREFUSED 127.0.0.1:27017
2 min
Terminal Error
MongoServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017
    at Timeout._onTimeout (node_modules/mongoose/lib/connection.js:748:12)

This error means nothing is listening on port 27017 — MongoDB is simply not running on your machine. Start it:

macOS — Homebrew

terminal
# Start MongoDB
brew services start mongodb-community

# Check it is running
brew services list | grep mongodb
# Should show: mongodb-community started

# Test with mongosh
mongosh
# If this opens a prompt — MongoDB is running

Linux (Ubuntu / Debian)

terminal
sudo systemctl start mongod

# Check status
sudo systemctl status mongod
# Should show: active (running)

# Enable auto-start on boot
sudo systemctl enable mongod

Windows

cmd
# Start MongoDB service
net start MongoDB

# Or via Services:
# Press Win+R → services.msc → find MongoDB → Start

After starting MongoDB, wait 2–3 seconds and retry your connection. MongoDB needs a brief moment to initialise before accepting connections.

2

Wrong Connection String Format

Invalid scheme / connection refused
2 min

The connection string format must match your MongoDB deployment type. Local MongoDB uses a different format from Atlas.

Local MongoDB — correct format

.env
# Local MongoDB — standard format
MONGODB_URI=mongodb://localhost:27017/mydb

# Local with auth
MONGODB_URI=mongodb://username:password@localhost:27017/mydb

# Local replica set
MONGODB_URI=mongodb://localhost:27017/mydb?replicaSet=rs0

MongoDB Atlas — correct format

.env
# Atlas — MUST use +srv format
MONGODB_URI=mongodb+srv://username:password@cluster0.abc123.mongodb.net/mydb

# NOT the standard format — wrong for Atlas:
# mongodb://cluster0.abc123.mongodb.net:27017  ← WRONG

Connect with correct error handling

server.js
require('dotenv').config()
const mongoose = require('mongoose')

mongoose.connect(process.env.MONGODB_URI)
  .then(() => console.log('✅ MongoDB connected'))
  .catch(err => {
    console.error('❌ MongoDB connection failed:', err.message)
    process.exit(1)
  })

Always use process.env.MONGODB_URI from a .env file. Never hardcode credentials in source code.

3

MongoServerError: Authentication Failed

Wrong username, password, or database user permissions
3 min
Terminal Error
MongoServerError: Authentication failed.
MongooseError: Authentication failed
    at Connection.onMessage (node_modules/mongodb/lib/cmap/connection.js:229:26)

Authentication failed means MongoDB received your connection but rejected your credentials. Causes: wrong username/password, user does not exist, user lacks permission for that specific database, or the password contains unencoded special characters.

Fix for MongoDB Atlas

  • Go to MongoDB Atlas dashboard
  • Click Security → Database Access
  • Click Edit on your database user
  • Click Edit Password → Autogenerate Secure Password
  • Copy the new password
  • Update MONGODB_URI in your .env file
  • Test connection with mongosh using the new credentials

Fix for local MongoDB — create user with correct permissions

mongosh
// Connect to admin database
use admin

// Create admin user
db.createUser({
  user: 'myuser',
  pwd: 'mypassword',
  roles: [
    { role: 'readWrite', db: 'mydb' }
  ]
})

// Verify user exists
db.getUsers()

Verify authentication database

.env
# If user is in admin db but connecting to app db:
MONGODB_URI=mongodb://user:pass@localhost:27017/mydb?authSource=admin
4

Atlas IP Not Whitelisted

ServerSelectionTimeoutError with Atlas
3 min
Terminal Error
MongoServerSelectionError: connection <monitor> to cluster.mongodb.net:27017 closed
    [server selection timed out after 30000 ms]

MongoDB Atlas requires you to whitelist IP addresses that are allowed to connect. If your current IP is not in the list, the connection times out silently — no error message, just a timeout.

Add your IP to Atlas

  • Open MongoDB Atlas dashboard at cloud.mongodb.com
  • Click Security → Network Access
  • Click Add IP Address
  • Click Add Current IP Address (for development)
  • Or enter 0.0.0.0/0 to allow all IPs (development only)
  • Click Confirm
  • Wait 60–90 seconds for the change to propagate
  • Retry your connection

For production — get your server IP

terminal on your server
# Get your server's public IP
curl ifconfig.me
# Add this exact IP to Atlas Network Access

Never leave 0.0.0.0/0 (allow all) in Atlas production. It allows any IP on the internet to attempt connections to your database. Only use it temporarily during development or debugging.

5

Special Characters in Password

Connection string malformed despite correct credentials
2 min

MongoDB connection strings are URLs. Special characters in your password (@ # $ ! & : /) must be URL-encoded. If they are not encoded, the connection string is parsed incorrectly and authentication fails.

Common special characters and their encodings

CharacterEncodedCharacterEncoded
@%40#%23
$%24!%21
&%26/%2F
:%3A %20

Encode automatically in Node.js

server.js
const username = encodeURIComponent(process.env.DB_USER)
const password = encodeURIComponent(process.env.DB_PASS)
const cluster  = process.env.DB_CLUSTER
const database = process.env.DB_NAME

const uri = `mongodb+srv://${username}:${password}@${cluster}/${database}`
mongoose.connect(uri)

The cleanest solution: use MongoDB Atlas auto-generated passwords. They avoid special characters entirely. Or use a password manager to generate a password using only alphanumeric characters.

6

MongoDB Connection Refused on Production Server

Self-hosted MongoDB on VPS / Ubuntu
5 min

On a self-hosted Linux server, ECONNREFUSED usually means MongoDB is either not running, configured to only accept localhost connections, or blocked by a firewall.

Check MongoDB is running

terminal
sudo systemctl status mongod

# If not running:
sudo systemctl start mongod
sudo systemctl enable mongod   # auto-start on reboot

Fix bind_ip to allow remote connections

/etc/mongod.conf
net:
  port: 27017
  bindIp: 127.0.0.1   # ← default, only localhost

# Change to allow remote connections:
net:
  port: 27017
  bindIp: 0.0.0.0     # ← all interfaces
terminal
sudo systemctl restart mongod

Open firewall port

terminal
# Ubuntu UFW
sudo ufw allow 27017/tcp

# Or allow only from specific IP
sudo ufw allow from YOUR_APP_SERVER_IP to any port 27017

Never open MongoDB port 27017 to the public internet (0.0.0.0). Only allow connections from your application server's specific IP address. An exposed MongoDB instance is a major security risk.

7

Add Connection Event Handlers

Debugging and monitoring connections
2 min

Adding event handlers gives you visibility into connection state — essential for debugging and for implementing reconnection logic.

server.js
mongoose.connect(process.env.MONGODB_URI)

mongoose.connection.on('connected', () => {
  console.log('✅ Mongoose connected to MongoDB')
})

mongoose.connection.on('error', (err) => {
  console.error('❌ Mongoose connection error:', err.message)
})

mongoose.connection.on('disconnected', () => {
  console.warn('⚠️  Mongoose disconnected from MongoDB')
})

// Check connection state anytime
// mongoose.connection.readyState:
// 0 = disconnected, 1 = connected, 2 = connecting, 3 = disconnecting
console.log('Connection state:', mongoose.connection.readyState)
8

Connection Retry Logic for Production

Prevent crashes when DB is briefly unavailable
3 min

In production, MongoDB may be temporarily unavailable during restarts or maintenance. Add retry logic so your app reconnects automatically instead of crashing.

database.js
const mongoose = require('mongoose')

const connectWithRetry = async (maxRetries = 5, delay = 5000) => {
  for (let attempt = 1; attempt <= maxRetries; attempt++) {
    try {
      await mongoose.connect(process.env.MONGODB_URI, {
        serverSelectionTimeoutMS: 5000,
      })
      console.log(`✅ MongoDB connected (attempt ${attempt})`)
      return
    } catch (err) {
      console.error(`❌ Connection attempt ${attempt}/${maxRetries} failed:`, err.message)
      if (attempt === maxRetries) {
        console.error('All connection attempts failed. Exiting.')
        process.exit(1)
      }
      console.log(`Retrying in ${delay / 1000} seconds...`)
      await new Promise(resolve => setTimeout(resolve, delay))
    }
  }
}

// Handle disconnection — reconnect automatically
mongoose.connection.on('disconnected', () => {
  console.warn('MongoDB disconnected. Reconnecting...')
  setTimeout(() => connectWithRetry(), 5000)
})

module.exports = connectWithRetry
server.js
const connectWithRetry = require('./database')

async function startServer() {
  await connectWithRetry()
  app.listen(process.env.PORT || 3000, () => {
    console.log('Server running')
  })
}

startServer()

How to Prevent Mongoose Connection Errors

Quick Error → Fix Reference

ECONNREFUSED 127.0.0.1:27017Start MongoDB: brew services start mongodb-community
Authentication failedReset password in Atlas → Database Access → Edit User
ServerSelectionTimeoutErrorWhitelist IP in Atlas → Security → Network Access
Invalid schemeUse mongodb+srv:// for Atlas, mongodb:// for local
Special char in URIURL-encode password: encodeURIComponent(password)

Frequently Asked Questions

What causes Mongoose connection error?+
The four most common causes are: MongoDB not running locally (start it with brew services start mongodb-community), wrong connection string format, authentication failure (wrong credentials), or your IP address not being whitelisted in MongoDB Atlas Network Access.
How do I fix MongoServerSelectionError connect ECONNREFUSED 127.0.0.1:27017?+
MongoDB is not running on your local machine. Start it: sudo systemctl start mongod (Linux) or brew services start mongodb-community (macOS). Then verify it is running with mongosh.
How do I fix MongoServerError authentication failed?+
Your MongoDB username or password is wrong. For Atlas: go to Database Access, edit your user, auto-generate a new password, and update your MONGODB_URI in .env. URL-encode special characters in passwords.
Mongoose connects locally but fails in production?+
Your production server IP is not whitelisted in Atlas Network Access. Go to Atlas → Security → Network Access → Add IP Address. For CI/CD, add 0.0.0.0/0 (allow all) only temporarily or use your deployment platform's static IP.
How do I check if MongoDB is running?+
Run mongosh on your machine. If it connects, MongoDB is running. On Linux: sudo systemctl status mongod. On macOS: brew services list | grep mongodb.
MongoDB URI with special characters not working?+
URL-encode special characters in your MongoDB password. @ becomes %40, # becomes %23, $ becomes %24. In Node.js: const pass = encodeURIComponent('p@ss'); const uri = `mongodb+srv://user:${pass}@cluster.mongodb.net/db`

Need Expert Help?

We Build Production-Grade Node.js & MongoDB Apps

Softplix builds full-stack applications with MongoDB and Node.js. Dealing with database architecture or connection issues in production? We can help.

Talk to an Engineer