Mongoose Connection Error— Fixed [Complete Guide 2026]
Also covers: MongoServerError authentication failed · MongoDB connection refused · ECONNREFUSED 127.0.0.1:27017
⚡ Identify Your Error in 30 Seconds
The exact error message tells you what is wrong. Check yours below:
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.
MongoDB Not Running Locally (ECONNREFUSED)
ECONNREFUSED 127.0.0.1:27017MongoServerSelectionError: 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
# 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 runningLinux (Ubuntu / Debian)
sudo systemctl start mongod
# Check status
sudo systemctl status mongod
# Should show: active (running)
# Enable auto-start on boot
sudo systemctl enable mongodWindows
# Start MongoDB service
net start MongoDB
# Or via Services:
# Press Win+R → services.msc → find MongoDB → StartAfter starting MongoDB, wait 2–3 seconds and retry your connection. MongoDB needs a brief moment to initialise before accepting connections.
Wrong Connection String Format
Invalid scheme / connection refusedThe connection string format must match your MongoDB deployment type. Local MongoDB uses a different format from Atlas.
Local MongoDB — correct format
# 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=rs0MongoDB Atlas — correct format
# 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 ← WRONGConnect with correct error handling
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.
MongoServerError: Authentication Failed
Wrong username, password, or database user permissionsMongoServerError: 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
// 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
# If user is in admin db but connecting to app db:
MONGODB_URI=mongodb://user:pass@localhost:27017/mydb?authSource=adminAtlas IP Not Whitelisted
ServerSelectionTimeoutError with AtlasMongoServerSelectionError: 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
# Get your server's public IP
curl ifconfig.me
# Add this exact IP to Atlas Network AccessNever 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.
Special Characters in Password
Connection string malformed despite correct credentialsMongoDB 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
| Character | Encoded | Character | Encoded |
|---|---|---|---|
| @ | %40 | # | %23 |
| $ | %24 | ! | %21 |
| & | %26 | / | %2F |
| : | %3A | %20 |
Encode automatically in Node.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.
MongoDB Connection Refused on Production Server
Self-hosted MongoDB on VPS / UbuntuOn 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
sudo systemctl status mongod
# If not running:
sudo systemctl start mongod
sudo systemctl enable mongod # auto-start on rebootFix bind_ip to allow remote connections
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 interfacessudo systemctl restart mongodOpen firewall port
# Ubuntu UFW
sudo ufw allow 27017/tcp
# Or allow only from specific IP
sudo ufw allow from YOUR_APP_SERVER_IP to any port 27017Never 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.
Add Connection Event Handlers
Debugging and monitoring connectionsAdding event handlers gives you visibility into connection state — essential for debugging and for implementing reconnection logic.
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)Connection Retry Logic for Production
Prevent crashes when DB is briefly unavailableIn production, MongoDB may be temporarily unavailable during restarts or maintenance. Add retry logic so your app reconnects automatically instead of crashing.
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 = connectWithRetryconst 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
- Store MONGODB_URI in .env — never hardcode credentials
- Enable MongoDB auto-start on boot: sudo systemctl enable mongod
- For Atlas: keep your IP whitelisted — check Network Access after changing networks
- URL-encode special characters in passwords or use auto-generated passwords
- Add connection event handlers so errors are visible in logs
- Use connection retry logic in production — never crash permanently on DB disconnect
- Wrap mongoose.connect() in try/catch and handle rejection with .catch()
Quick Error → Fix Reference
Frequently Asked Questions
What causes Mongoose connection error?+−
How do I fix MongoServerSelectionError connect ECONNREFUSED 127.0.0.1:27017?+−
How do I fix MongoServerError authentication failed?+−
Mongoose connects locally but fails in production?+−
How do I check if MongoDB is running?+−
MongoDB URI with special characters not working?+−
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