MongoDB connection error: MongoTimeoutError: Server selection timed out after 30000 ms
Asked Answered
D

30

60

I am trying to create a fullstack app reading the following tutorial:

https://medium.com/javascript-in-plain-english/full-stack-mongodb-react-node-js-express-js-in-one-simple-app-6cc8ed6de274

I followed all steps and then tried to run:

node server.js

But I got the following error:

MongoDB connection error: MongoTimeoutError: Server selection timed out after 30000 ms at Timeout._onTimeout (C:\RND\fullstack_app\backend\node_modules\mongodb\lib\core\sdam\server_selection.js:308:9) at listOnTimeout (internal/timers.js:531:17) at processTimers (internal/timers.js:475:7) { name: 'MongoTimeoutError', reason: Error: connect ETIMEDOUT 99.80.11.208:27017 at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1128:14) { name: 'MongoNetworkError', [Symbol(mongoErrorContextSymbol)]: {} }, [Symbol(mongoErrorContextSymbol)]: {} } (node:42892) UnhandledPromiseRejectionWarning: MongoTimeoutError: Server selection timed out after 30000 ms at Timeout._onTimeout (C:\RND\fullstack_app\backend\node_modules\mongodb\lib\core\sdam\server_selection.js:308:9) at listOnTimeout (internal/timers.js:531:17) at processTimers (internal/timers.js:475:7)

My code at server.js is as follows:

const mongoose = require('mongoose');
const router = express.Router();

// this is our MongoDB database
const dbRoute =
    'mongodb+srv://user:<password>@cluster0-3zrv8.mongodb.net/test?retryWrites=true&w=majority';

mongoose.Promise = global.Promise;

// connects our back end code with the database
mongoose.connect(dbRoute, 
    {   useNewUrlParser: true,
        useUnifiedTopology: true
    });

let db = mongoose.connection;

db.once('open', () => console.log('connected to the database'));

Any suggestions?

Dissimulate answered 3/12, 2019 at 17:22 Comment(6)
Did you changed user:password to your username and password in connection string?Perlaperle
@ShivamSood Yes, I didDissimulate
To add to the info, I tried to connect using MongoDB compass community but it gave the same error. Can it be some settings at atLas Mongodb?Dissimulate
application is running well with local MongoDB "mongodb://127.0.0.1/FullStack". Appears connectivity to atlas MongoDB is the issue.Dissimulate
I am able to solve it. Firewall was blocking access,the same could be tested with this: portquiz.net:27017Dissimulate
Check here if using ProtonVPN: mongodb.com/community/forums/t/…Impressure
B
67

I wasted whole day on this because the whitelist suggestion was not my issue (I'm running in docker compose with --bind_ip option set properly and I can see the Connection accepted in the mongo logs each time my client tried to connection).

It turns out, I simply needed to add this to the end of my connection string in the code:

?directConnection=true

connection string:

mongodb://myUserId:myPassword@mongodb/myDatabase?directConnection=true

I hope mongodb documents this better because I only stumbled across it from looking at the mongosh logs when I connected using that client.

Biauriculate answered 2/12, 2021 at 17:47 Comment(9)
OMG. Cost me a day until I found this tip!! Thanks!Ordain
I was so happy to see this answer but it didn't help me unfortunautly as I'm using 'SRV' connection string. This is the error I'm getting after trying this solutions: "MongoAPIError: SRV URI does not support directConnection"Alate
This answer is just soo helpful :)Giraldo
This is really helpful, wasted days before I found this.Dannie
directConnection=true is not recommended for production environmentsProsody
@Prosody I haven't seen this mention anywhere. Do you have a source?Biauriculate
MongoDB replica set is a group of connected instances that store the same set of data. This configuration provides data redundancy and high data availability. By enabling directConnection=true, you are losing this feature. mongodb.com/docs/drivers/go/current/fundamentals/connectionProsody
Useful for an initial connection to an instance before the replica set has been initialized. In particular, when you're connecting in order to initialize the replica set!Moorings
@Alate can you instead use the connection string you see in mongosh?Biauriculate
B
53

just go to mongodb atlas admin panel.Go in security tab>Network Access> Then whitelist your IP by adding it

See this image to locate the particular menu

Note:Check your IP on google then add it

Bender answered 14/12, 2019 at 19:14 Comment(4)
Did that, but no luck. Rather I allowed all IPs, still did not workDissimulate
bro, have you set up the DB configuration properlyBender
I have created roles for db access: username: arvind Authentication method: SCRAM MongoDBRoles: atlasAdmin@admin Do I need to create something in cluster or 'Data Lake'?Dissimulate
able to solve it, everything was correct, but the firewall was blocking access to port 27017 same can be tested here:portquiz.net:27017Dissimulate
T
18

In my case, this issue happened after NodeJS version upgrade from Node 14 to Node 17 and the mongoose was not connecting to MongoDB in local.

Solution - In connection string, change localhost to 127.0.0.1.

Ref - https://github.com/Automattic/mongoose/issues/10917#issuecomment-957671662

Traditor answered 15/1, 2022 at 13:21 Comment(4)
Thank you. Same for me running Node 17.4.0 - There's probably a way to get Node resolving localhost but makes no difference to me so using 127.0.0.1 was a good quick fixPenrod
Simplest and most correct answer.Paripinnate
Thank you, same for me upgrading from Node 14 to Node 18Lodger
Thanks! I had the same problem after upgrading to Node 18, this fixed it. Node 20 works again with either localhost or the IP.Piccolo
A
10

Sometimes this error occurs due to the IP Address given access to in your database.

Mind you, your application can be working well then come up with such an error. Anytime this happens, most times your IP address has changed, which is not on the whitelist of addresses allowed. (IP addresses can be dynamic and are subject to change)

All you have to do is to update the whitelist with your current IP addresses

Angloindian answered 11/2, 2020 at 9:56 Comment(1)
What if 0.0.0.0 is in ip address which includes my IP address and the problem still persists?Frontal
H
9

I got the same error. These are the steps I followed for resolve it

  1. Log into your Mongo Atlas account
  2. Go to the security tab -> Network Access -> Then whitelist your IP
  3. Then go to the security tab -> Database Access -> and delete your current user.
  4. Create a new user by providing new username and password.
  5. Provide that newly created username and password in the .env file or mongoose.connect method

After these steps it worked as usual. hope this will help you guys.

Halfhearted answered 9/2, 2020 at 0:56 Comment(2)
I would suggest another first step before current first step saying "Log into your Mongo Atlas account". It would make things much clearer.Maryannmaryanna
Thank you! I needed the Network Access step.Phiz
W
8

Sometimes it will also happen when your MongoDB services are turned OFF.

Here are the steps to Turn ON the MongoDB Services:

  1. Press window key + R to open Run window.
  2. Then type services.msc to open services window.
  3. Then select MongoDB server, right-click on it, finally click on the start.
Wheatworm answered 4/6, 2020 at 13:30 Comment(3)
Worked for me. Thank you!! I was getting " UnhandledPromiseRejectionWarning: MongooseServerSelectionError: connect ECONNREFUSED" earlier. This hack is awesome!Heffner
not seeing any MongoDB server in open services window.Laufer
that worked for me as well if you are using MongoDB in local that's the answer.Induct
N
6

Ensure that the "<" and ">" are removed when you replace the user and password fields. This worked for me

Nauseating answered 22/1, 2020 at 4:16 Comment(0)
P
5

Are you using any Antivirus, Firewall, VPN or on the restricted network (e.g. work/commercial Wi-Fi/LAN connection)? Then try to turn it off/reconnect to a different network. Some IPs/connections might be blocked by the administrator of a network that you're using or simply antivirus might have firewall policies. Even though if you have 0.0.0.0 in your IP Address at the MongoDB Atlas.

Pademelon answered 14/2, 2020 at 13:36 Comment(0)
D
3

I am able to solve the issue. Everything was fine, but the firewall was blocking access to port 27017. connectivity can be tested at http://portquiz.net:27017/ or using telnet to the endpoint which can be retrieved from clusters->Metrics.

Thanks, everybody for the suggestions

Dissimulate answered 18/12, 2019 at 14:54 Comment(1)
I had the same issue, I'm surprised your solution is so buried, maybe you should mark it as accepted? All I had to do was add 27017 to outgoing TCP ports.Giannini
U
2

Whitelist your connection IP address. Atlas only allows client connections to the cluster from entries in the project’s whitelist. The project whitelist is distinct from the API whitelist, which restricts API access to specific IP or CIDR addresses.

NOTE

You can skip this step if Atlas indicates in the Setup Connection Security step that you have already configured a whitelist entry in your cluster. To manage the IP whitelist, see Add Entries to the Whitelist.

If the whitelist is empty, Atlas prompts you to add an IP address to the project’s whitelist. You can either:

Click Add Your Current IP Address to whitelist your current IP address.

Click Add a Different IP Address to add a single IP address or a CIDR-notated range of addresses.

For Atlas clusters deployed on Amazon Web Services (AWS) and using VPC Peering, you can add a Security Group associated with the peer VPC.

You can provide an optional description for the newly added IP address or CIDR range. Click Add IP Address to add the address to the whitelist.

Unruffled answered 25/12, 2019 at 7:46 Comment(0)
P
1

You can remove { useUnifiedTopology: true } flag and reinstall mongoose dependecy! it worked for me.

Packaging answered 11/12, 2019 at 15:23 Comment(1)
it gives the following error when { useUnifiedTopology: true } removed: (node:10020) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.Dissimulate
R
1

To anyone still struggling through this issue. I resolved this issue by setting all the parameters like username, password and dbName in mongoose options itself.

Earlier the code was like this. (When I was getting the error).

import mongoose from "mongoose";
mongoose.Promise = require("bluebird");

let dbName = process.env.DB_NAME;
const dbAddress = process.env.DB_HOST;
const dbPort = process.env.DB_PORT;
if(!dbName || !dbAddress || !dbPort){
    throw new Error("Mongo error unable to configuredatabase");
}

let options = {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    user:process.env.DB_USER,
    pass: process.env.DB_PASS
};

mongoose.connect(`mongodb://${dbAddress}:${dbPort}/${dbName}`, options).catch(err => {
    if (err.message.indexOf("ECONNREFUSED") !== -1) {
        console.error("Error: The server was not able to reach MongoDB. Maybe it's not running?");
        process.exit(1);
    } else {
        throw err;
    }
});

Note that url in mongo connect. mongodb://${dbAddress}:${dbPort}/${dbName}.

New code without error.

import mongoose from "mongoose";
mongoose.Promise = require("bluebird");

let dbName = process.env.DB_NAME;
const dbAddress = process.env.DB_HOST;
const dbPort = process.env.DB_PORT;
// console.log("process.env", process.env)
if(!dbName || !dbAddress || !dbPort){
    throw new Error("Mongo error unable to configuredatabase");
}

let options = {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    user:process.env.DB_USER,
    pass: process.env.DB_PASS,
    dbName: dbName
};

mongoose.connect(`mongodb://${dbAddress}:${dbPort}`, options).catch(err => {
    if (err.message.indexOf("ECONNREFUSED") !== -1) {
        console.error("Error: The server was not able to reach MongoDB. Maybe it's not running?");
        process.exit(1);
    } else {
        throw err;
    }
});

Note the options and the url.

This is my local env. Not production env.

Hope It'll be helpful.

Resound answered 12/4, 2020 at 9:35 Comment(0)
T
1

try to specify the node driver, version 2,2,12 in cluster --> connect --> connect your application. new string must be with mongodb://. use this string to connect. do not forget to enter a password

Tremolo answered 21/4, 2020 at 17:59 Comment(0)
U
1

Most of the answers present in this thread should fix you're issue, I tried all the answers and whitelisted all the IP's but still I was not able to connect to the database.

Interestingly, my system was connected to a VPN while I was trying to connect to the mongo atlas. So, I just disconnected the VPN and was able to connect to the db. This was just an simple issue due to which I was not able to connect to the database.

Unloose answered 21/7, 2022 at 15:2 Comment(2)
Confirmed. I was connected to a VPN and it blocked me although it was set as 0.0.0.0 for the IP range on the network access. It seems Atlas MongoDB blocks IP ranges of some known proxies.Jazzy
Check here if using ProtonVPN: mongodb.com/community/forums/t/…Impressure
N
0

i was has this problem, to me the solution was check if my ip be configured correctly and before confirm in this screen

enter image description here

Negron answered 11/12, 2019 at 0:49 Comment(1)
I found the solution. The issue was in firewall settings at my network system. portquiz.net:27017 can be used to test if the connection is through. Though i did not change the firewall as that is managed by network admins at my end, but once the firewall corrected its working now. Thanks everybody for suggestions.Dissimulate
A
0

Please Check your Password, Username OR IP configuration. Mostly "Server selection timed out after 30000 ms at Timeout._onTimeout" comes whenever your above things are not matched with your server configuration.

Alban answered 16/12, 2019 at 11:57 Comment(1)
it was a firewall issue at my end. I corrected it and now its workingDissimulate
V
0

Try to make new User in Database Access with the default Authentication Method which is "SCRAM". Then make a new Cluster for that. It worked for me! My server.js file

const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');

require('dotenv').config();

const app = express();
const port = process.env.PORT || 5000;

app.use(cors());
app.use(express.json());

//const uri = process.env.ATLAS_URI;
mongoose.createConnection("mongodb+srv://u1:[email protected]/test", { userNewParser: true, useCreateIndex: true,  useUnifiedTopology: true}
    );

const connection = mongoose.connection;
connection.once('once', () => {
    console.log(`MongoDB databse connection established successfully`);
})

app.listen(port, () => {
    console.log(`Server is running on port: ${port}`);
});
Vtol answered 2/1, 2020 at 12:22 Comment(0)
W
0

What is your mongoose version? because there is an issue with a certain mongoose version. Please visit this link for more details "https://github.com/Automattic/mongoose/issues/8180". Anyway, I was facing the same issue but after using an older version (5.5.2), it worked for me. Please give a try and let me know what happened.

Wapiti answered 6/1, 2020 at 13:40 Comment(1)
I was running into the same issue, however, I frequently develop with my VPN toggled on and off. By turning my VPN on again, I managed to connect to the DB. I'm hoping this issue is temporary, because I can't always have my VPN on.Scarfskin
T
0

It might basically be because of an npm update. I just updated to npm v 6.13.7. and I began to get that error.

Following instructions from @Matheus, I commented the line "{ useUnifiedTopology: true }" and I was able to get through it.

I updated mongoose and everything works fine.

Twosided answered 5/2, 2020 at 11:29 Comment(0)
C
0

I had the same issue. I could connect from MongoDB Compass or my Node app using the connection strings Atlas gave me. I resolved it by adding my IP Address into the Whitelist in Atlas.

Craunch answered 22/3, 2020 at 20:2 Comment(0)
M
0

For anyone who may face this problem with mongoose v6+ and nodejs and white listing your ip has not solved it or changing from localhost to 127.0.0.1.

Solution Set the following options for the mongoose client connection options:

 mongoose.connect(url, { 
                        maxIdleTimeMS: 80000,
                        serverSelectionTimeoutMS: 80000,
                        socketTimeoutMS: 0,
                        connectTimeoutMS: 0
                        }

These options stop the mongoose client from timining out the connection before it selects a primary from the DB cluster.

Please remember to set any other options relevant to your setup like if you are running a cluster, make sure to set the replicaSet option or if you have authentication enabled, set the authSource option or the database you are connecting to dbName.

Some of these options can be set in the connection string.

The full list of options can be found here: https://mongodb.github.io/node-mongodb-native/4.2/interfaces/MongoClientOptions.html#authSource

Mise answered 20/7, 2022 at 9:38 Comment(0)
D
0

If your config is alright and still the error shows up, it maybe because of too much data in the db (Like for me, I am using the free tier for testing my app where I upload posts and the posts are images with some description), so I just deleted the db and it worked fine after that. Hope this helps someone.

Dipietro answered 23/1, 2023 at 5:4 Comment(0)
J
0

Your problem is that you don't have MongoDB installed on your computer. Once you download it you can change

mongoose.connect('mongodb://localhost:27017/blog')

to

mongoose.connect('mongodb://127.0.0.1/blog')
Jovi answered 13/6, 2023 at 23:9 Comment(0)
C
0

This error also occurs when the declared hosts do not match the specified replica set. e.g.mongodb://cluster-name1-shard-00-00.wplyy.mongodb.net:27017,cluster-name1-shard-00-01.wplyy.mongodb.net:27017,cluster-name1-shard-00-02.wplyy.mongodb.net:27017/my-database?ssl=true&authSource=admin&replicaSet=other-cluster-name-shard-0

Corabelle answered 15/1 at 10:33 Comment(0)
S
0

LISTEN I EXPERIENCED A SIMILAR SITUATION BEFORE EVEN THOUGH I ALREADY SET MY IP: 0.0.0.0/0

just log in to Mongo Atlas (Click on your project) then go to the network option on the left side it will be towards the bottom of the menu.

Just change your IP use choose my current IP option.

Image to navgate

Serafinaserafine answered 31/3 at 20:34 Comment(0)
J
0

In my case i blocked the ip scan in the server using a script and because of that my app could not connect to db

Check the scripts you have ran

Jounce answered 10/5 at 5:12 Comment(0)
A
0

Finally found the solution after so many trial and error. All I had to do was to add this at the end of my Mongodb URI :

mongodb+srv://<username>:<password>@YourAppName.wo509tr.mongodb.net/**?retryWrites=true&w=majority&appName=YourAppName**

retryWrites=true&w=majority&appName=YourAppName <- this was the part i was missing

Alkali answered 16/5 at 13:47 Comment(0)
B
0

This solution fixed the problem for me.

const client = new MongoClient(uri, {
  serverApi: {
    version: ServerApiVersion.v1,
    strict: true,
    deprecationErrors: true,
    directConnection: true,
  },
});
Baalbeer answered 28/6 at 14:30 Comment(0)
B
-1

This must be a temporary network issue. Please try to connect after some time and hopefully it should be fine. but make sure you white list your ip address.

Belligerency answered 14/11, 2022 at 9:15 Comment(0)
S
-2

I have solved this problem by using the following way, use a callback.

const uri = '';

mongoose
  .connect(uri, { useNewUrlParser: true, useUnifiedTopology: true }, () => {
    console.log("we are connected");
  })
  .catch((err) => console.log(err));
Styptic answered 24/5, 2020 at 16:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.