Back to Blog
Bug Fixes•1 min read

Fix 'MongoNetworkError: connect ECONNREFUSED' in Node.js

Scaleup Infotech Team
Scaleup Infotech Team

Custom Software & Business Automation

Node.jsMongoDBMongooseAtlas

In this guide

A simple guide to this issue: 'MongoNetworkError: connect ECONNREFUSED' in Node.js. Learn why it happens, what to check first, and how to fix it.

ECONNREFUSED from MongoDB means your driver reached an address but nothing answered. With Atlas it is almost always the IP allowlist; locally it is usually the service not running.

The Error

MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017

Local MongoDB: Is It Running?

bash
# macOS (Homebrew)
brew services start mongodb-community

# Linux
sudo systemctl start mongod
sudo systemctl status mongod

Atlas: Allowlist Your IP

In Atlas → Network Access, add your current IP. For a server with a changing IP, you may temporarily allow 0.0.0.0/0 (any IP) — but lock it down for production.

Verify the Connection String

javascript
// Use the SRV string for Atlas; URL-encode special characters in the password
const uri = process.env.MONGODB_URI; // mongodb+srv://user:pass@cluster.mongodb.net/db

await mongoose.connect(uri, { serverSelectionTimeoutMS: 5000 });

Password Special Characters

An @, :, or / in your password breaks the URI. URL-encode it (@ → %40) or the driver will parse the host wrong and 'refuse' to connect.

Share this article:

Keep Reading

Ready to implement these ideas?

Discuss Your Project