Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set MongoClient connection timeout?

I have a server which first connects to MongoDB instance, then starts web server. If MongoDB instance is not available, there is no point to start web server, so I think I need to somehow set a timeout to, say 5 seconds.

How do I do it?

Here is my code:

MongoClient.connect(Config.database.url).then((db) => {
        console.log('Connected to MongoDB');
        databaseInstance = db;
       // start web server
    })
like image 697
Sergei Basharov Avatar asked Oct 11 '16 14:10

Sergei Basharov


2 Answers

you can use "connectTimeoutMS" like so

MongoClient.connect(Config.database.url, {
    server: {
        socketOptions: {
            connectTimeoutMS: 5000
        }
    }
}).then((db) => {
    console.log('Connected to MongoDB');
    databaseInstance = db;
   // start web server
})

Here is more information about it...

http://mongodb.github.io/node-mongodb-native/2.0/reference/connecting/connection-settings/ https://mongodb.github.io/node-mongodb-native/driver-articles/mongoclient.html

like image 33
tanaydin Avatar answered Oct 11 '22 00:10

tanaydin


  • To define the timeout for the initial connection use serverSelectionTimeoutMS.
  • To define the timeout for the ongoing connection connectTimeoutMS

MongoDB 3.6 connection example:

const client = new MongoClient(Config.database.url, {
  connectTimeoutMS: 5000,
  serverSelectionTimeoutMS: 5000
})

client.connect(err => {
  console.log('Connected to MongoDB')
  // ..
})

See the official docs for serverSelectionTimeoutMS

like image 183
Ricky Boyce Avatar answered Oct 10 '22 22:10

Ricky Boyce