如何设置MongoClient连接超时? [英] How to set MongoClient connection timeout?

查看:837
本文介绍了如何设置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

这篇关于如何设置MongoClient连接超时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆