如何设置MongoClient连接超时?

问题描述:

我有一个服务器,该服务器首先连接到MongoDB实例,然后启动Web服务器.如果MongoDB实例不可用,则没有必要启动Web服务器,因此我认为我需要以某种方式将超时设置为5秒.

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.

我该怎么做?

这是我的代码:

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

您可以像这样使用"connectTimeoutMS"

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