MongoServerSelectionError: connection timed out with NodeJS and Express

Viewed 5077

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?

3 Answers

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

You could try passing it in as an async function, and then try and catch it.

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

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

const connect = async () => {
    try {
        const client = await mongodb.connect(connectionString, { useNewUrlParser: true });
        console.log('connected to mongodb');
        return client;
    } catch (error) {
        console.log(error);
    }
}
  • 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!

Related