如何设置MongoClient连接超时?

时间:2016-10-11 14:41:59

标签: javascript mongodb

我有一台服务器首先连接到MongoDB实例,然后启动Web服务器。如果MongoDB实例不可用,那么启动Web服务器是没有意义的,所以我想我需要以某种方式设置超时,比如5秒。

我该怎么做?

这是我的代码:

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

2 个答案:

答案 0 :(得分:1)

要定义与数据库的初始连接和正在进行的连接的超时,可以分别使用选项Sub GetSheets() 'Update ExcelJunction.com Path = "C:\Users\chad.carlisle\Documents\CBMS\" Filename = Dir(Path & "*.xlsx") Do While Filename <> "" Workbooks.Open Filename:=Path & Filename, ReadyOnly:=True For Each Sheet In ActiveWorkbook.Sheets Sheet.Copy After:=ThisWorkbook.Sheets(1) Next Sheet Workbooks(Filename).Close Filename = Dir() Loop End Sub serverSelectionTimeoutMS

MongoDB 3.6连接示例:

connectTimeoutMS

由于某些原因,const client = new MongoClient(Config.database.url, { connectTimeoutMS: 5000, serverSelectionTimeoutMS: 5000 }) client.connect(err => { console.log('Connected to MongoDB') // .. }) 似乎尚未记录在案: https://mongodb.github.io/node-mongodb-native/3.6/reference/connecting/connection-settings/

答案 1 :(得分:0)

你可以像这样使用“connectTimeoutMS”

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

以下是有关它的更多信息......

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