How to Fix Mongoose Connection Error in Node.js
In this tutorial, you'll learn about How to Fix Mongoose Connection Error in Node.js. We cover key concepts, practical examples, and best practices.
The Problem
Your Node.js app using Mongoose fails to connect to MongoDB with error MongooseServerSelectionError: connect ECONNREFUSED or Authentication failed, often because the URI is wrong, the database is not running, or IP access is restricted by the firewall or Atlas network settings.
Quick Fix
Verify the MongoDB Connection URI
node -e "
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/test')
.then(() => console.log('Connected'))
.catch(err => console.error('Failed:', err.message));
"
# Failed: connect ECONNREFUSED ::1:27017
A ECONNREFUSED error means MongoDB is not running on that host and port. Start MongoDB with mongod or sudo systemctl start mongod and verify the connection string matches your setup.
Use the Correct Format for Atlas or Authenticated URIs
node -e "
const mongoose = require('mongoose');
const uri = 'mongodb+srv://user:password@cluster0.abcde.mongodb.net/mydb?retryWrites=true&w=majority';
mongoose.connect(uri)
.then(() => console.log('Connected to Atlas'))
.catch(err => console.error('Auth failed:', err.message));
"
# Connected to Atlas
For MongoDB Atlas, use <a href="/databases/mongodb/">mongodb</a>+srv:// and URL-encode special characters in the password (e.g., @ becomes %40). The retryWrites parameter ensures resilience against network interruptions.
Handle Connection Events for Resilience
node -e "
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/test');
mongoose.connection.on('connected', () => console.log('Connected'));
mongoose.connection.on('error', err => console.error('Error:', err.message));
mongoose.connection.on('disconnected', () => console.log('Disconnected'));
"
# Connected
Register event listeners on mongoose.connection to monitor connection state and implement reconnection logic. The disconnected event is particularly useful for logging and alerting.
Set Connection Timeout and Retry Options
node -e "
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/test', {
serverSelectionTimeoutMS: 5000,
heartbeatFrequencyMS: 10000
}).catch(err => console.error('Failed:', err.message));
"
# Failed: Server selection timed out after 5000ms
Set serverSelectionTimeoutMS to fail fast instead of hanging for 30 seconds by default. This is especially important in production to provide quick feedback when the database is unavailable.
Check Node.js and npm Versions
node --version
# v18.17.0
npm --version
# 9.6.7
Verify your runtime versions before troubleshooting module resolution or compatibility issues. Outdated versions of Node.js or npm are a common source of mysterious errors. Use nvm to manage multiple Node versions side by side.
Additional Troubleshooting
# Check the error message and stack trace for more context
echo "Review the full error output to identify the root cause"
If the above steps do not resolve the issue, examine the complete error message and stack trace. Often the key detail is in the middle of the traceback rather than the final line. Search for the error message in the project documentation or issue tracker for additional solutions.
Use Connection Pool Configuration
node -e "
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/test', {
maxPoolSize: 10,
minPoolSize: 2
}).then(() => console.log('Connected with pool'));
"
Configure maxPoolSize and minPoolSize to control the number of concurrent connections. A pool that is too small causes queuing delays, while a pool that is too large wastes server resources.
Prevention
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro