【问题标题】:How to handle mongo db unable to connect issue with Mongoose and NodeJs?如何处理 mongo db 无法连接 Mongoose 和 NodeJs 的问题?
【发布时间】:2013-10-16 10:40:39
【问题描述】:

我们的 Nodejs 应用程序使用 Mongoose for MongoDB。我们的应用程序在无法连接到 MongoDB 数据库时崩溃。我们正在使用MongoLab

在 Node JS 应用程序中处理数据库连接问题的最佳方法是什么?

【问题讨论】:

    标签: node.js mongodb mlab


    【解决方案1】:

    只需处理相关事件的错误:

    // If the connection throws an error
    connection.on('error',function (err) {
      // Do something here
    });
    
    // When the connection is disconnected
    connection.on('disconnected', function () {
      // Do something else here
    });
    

    当然,在运行查询时,非常建议在继续之前检查回调函数的err 参数。

    【讨论】:

    • 谢谢。它工作得很好。但是当连接出错时,请求等待响应很长时间。有什么办法可以超时吗?连接超时和套接字超时有什么区别吗?
    • 据我所知,套接字超时意味着连接超时。您可以通过在调用connect 时将其作为选项传递来定义连接超时:mongoose.connect(url, { server: { socketOptions: { connectTimeoutMS: 1000 }}}, function(err) { ... });
    • 谢谢。但是MongoLab博客分别讲了连接超时和socket超时blog.mongolab.com/2013/10/do-you-want-a-timeout
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-12-21
    • 2019-01-03
    • 2012-01-01
    • 2021-01-04
    • 1970-01-01
    • 1970-01-01
    • 2021-08-26
    相关资源
    最近更新 更多