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?
This worked for me!
Check your connection string, make sure it is properly constructed. It could be missing something, or is using the wrong protocol.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With