10

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
    })

2 Answers 2

14
  • 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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks - this is exactly what I (and I suspect OP, despite marking the other answer as correct) was looking for. connectTimeoutMS wasn't timing out the initial connection. serverSelectionTimeoutMS is exactly what we want.
serverSelectionTimeoutMS specifies how long (in milliseconds) to block for server selection before throwing an exception - it is not just for the initial connection as implied in this answer
4

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

1 Comment

I don't actually think this is what the OP wants (despite them marking it as accepted). connectTimeoutMS isn't what most people would consider the connection timeout. See @Ricky's answer below.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.