πŸ”§ Error Fixes
Β· 1 min read

MongoDB: Connection Timeout β€” How to Fix It


MongoServerSelectionError: connection timed out means your app can’t reach the MongoDB server within the timeout period.

What causes this error

  1. MongoDB Atlas IP whitelist β€” your IP isn’t allowed
  2. Wrong connection string β€” typo in host, port, or credentials
  3. Network/firewall β€” port 27017 is blocked
  4. 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