MongoDB: MongoTimeoutError: Server selection timed out
Educational use only. Content explains errors and defensive fixes for systems you own or are authorised to test. Do not use any technique here to access data, accounts, or networks without permission.
Root Cause
This error signifies that the MongoDB driver in your application was unable to establish a connection to the database server within the specified timeout limit. In a cloud environment (like MongoDB Atlas), this is almost always caused by network security configuration. The most common culprit is IP Whitelisting: the IP address of the server running your application has not been added to the database's allowed Network Access list. Other causes include incorrect connection strings, DNS resolution failures, or the database cluster being physically down or paused.
Fix / Solution
Log into your MongoDB Atlas (or equivalent) control panel and navigate to Network Access. Add the public IP address of your application server (or `0.0.0.0/0` for temporary testing, though this is insecure). Double-check your connection URI, ensuring the username, password, and cluster address are correct. Ensure your application environment variables are loaded properly.
Code Snippet
// ❌ Mongoose connection fails due to IP restriction
mongoose.connect('mongodb+srv://user:pass@cluster.mongodb.net/test');
// ✅ Solution: No code change required.
// Fix is applied in the MongoDB Atlas dashboard -> Network Access -> Add IP Address.