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