MongoServerSelectionError: connection timed out means your app canβt reach the MongoDB server within the timeout period.
What causes this error
- MongoDB Atlas IP whitelist β your IP isnβt allowed
- Wrong connection string β typo in host, port, or credentials
- Network/firewall β port 27017 is blocked
- MongoDB not running β the server is down
Fix 1: Check Atlas IP whitelist
In MongoDB Atlas β Network Access β Add your current IP or 0.0.0.0/0 for development (not production).
Fix 2: Verify connection string
# Test the connection
mongosh "mongodb+srv://user:password@cluster.mongodb.net/mydb"
# Common mistakes:
# - Special characters in password (URL-encode them)
# - Wrong cluster name
# - Missing /database at the end
Fix 3: Check network connectivity
# Can you reach the server?
ping cluster.mongodb.net
telnet cluster.mongodb.net 27017
# Check DNS resolution
nslookup cluster.mongodb.net
Fix 4: Increase connection timeout
mongoose.connect(uri, {
serverSelectionTimeoutMS: 10000, // 10 seconds (default 30s)
connectTimeoutMS: 10000,
});
Related: MongoDB cheat sheet Β· MongoDB: Duplicate Key Error fix Β· MongoDB vs PostgreSQL