关闭错误的猫鼬连接 [英] Close erroneous mongoose connection

查看:79
本文介绍了关闭错误的猫鼬连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当猫鼬无法连接到数据库时,如何正确结束脚本?

When mongoose fails to connect to the DB, how do I properly end the script?

以下内容一直在运行:

var mongoose = require('mongoose');

mongoose.connect('mongodb://localhost/db', function(err){
    if (err) {
        console.log(err);
        mongoose.connection.close();
    }
});

我也尝试过mongoose.disconnect(),结果相同.

I also tried mongoose.disconnect() with the same result.

最简单的方法显然是throw err;,但这似乎是解决该问题的残酷方法.

The easiest way is obviously throw err; but this seems a brutal hammer solution to the problem.

推荐答案

如果connect函数失败(即err != null),则表示连接状态未打开,因此无法关闭或断开连接.

If the connect function failed (i.e. err != null) that means the connection state is not open, therefore, you can't close or disconnect it.

要向自己证明,可以检查mongoose.connection.readyState(以下是可用值).

To prove it to yourself, you can check the mongoose.connection.readyState (here are the available values).

我可以建议使用mongoose.connection.on('error', cb);来更好地处理连接错误.

May I suggest using mongoose.connection.on('error', cb); to better handle connection errors.

这篇关于关闭错误的猫鼬连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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