Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoServerSelectionError: connection timed out with NodeJS and Express

I am attempting to connect to a Mongo database running on a VPS with NodeJS and Express. Here is my code:

const app = express();
const MongoClient = require('mongodb').MongoClient

const connectionString = "mongodb://[Username]:[Password]@[IP Address]:[Port Number]/[Database]"

MongoClient.connect(connectionString, { useUnifiedTopology: true }, (err, client) => {
  if (err) return console.error(err)
  console.log('Connected to Database')
})

app.get('/', function(req, res) {
  res.send('Hello World')
})

app.listen(3000, function() {
  console.log('listening on 3000')
})

I am expecting it to print 'Connected to Database' but instead it throws the following exception:

MongoServerSelectionError: connection timed out
    at Timeout._onTimeout (/home/[user]/node_modules/mongodb/lib/core/sdam/topology.js:438:30)
    at listOnTimeout (internal/timers.js:549:17)
    at processTimers (internal/timers.js:492:7) {
  reason: TopologyDescription {
    type: 'Unknown',
    setName: null,
    maxSetVersion: null,
    maxElectionId: null,
    servers: Map { '[IP Adress]:[Port Number]' => [ServerDescription] },
    stale: false,
    compatible: true,
    compatibilityError: null,
    logicalSessionTimeoutMinutes: null,
    heartbeatFrequencyMS: 10000,
    localThresholdMS: 15,
    commonWireVersion: null
  }
}

I am able to succesfully access the IP address on my browser. It leads me to the default index page for an Apache webserver. Running show users inside the mongo terminal after selecting my database gives the following response:

{
    "_id" : "[Database].[Username]",
    "userId" : UUID("1545d0ec-1309-4e40-82e4-7777afb266fe"),
    "user" : [Username],
    "db" : [Database],
    "roles" : [
        {
            "role" : "readWrite",
            "db" : [Database]
        }
    ],
    "mechanisms" : [
        "SCRAM-SHA-1",
        "SCRAM-SHA-256"
    ]
}

What would be the appropriate steps to continue debugging this? Is there any more information I should provide?

like image 214
Elias Mäkelä Avatar asked Nov 15 '25 13:11

Elias Mäkelä


2 Answers

  • Go to MongoDB and Sign in;
  • Check your Network access;
  • If your IP access list is empty, add a new IP access, otherwise, delete the current IP and add a new ip. [Choose your current IP address].

This worked for me!

like image 99
Cristóvão Fábio Avatar answered Nov 18 '25 08:11

Cristóvão Fábio


Check your connection string, make sure it is properly constructed. It could be missing something, or is using the wrong protocol.

like image 22
C. Bess Avatar answered Nov 18 '25 08:11

C. Bess



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!