【问题标题】:How to make a Mongoose connection fail gracefully如何使猫鼬连接优雅地失败
【发布时间】:2012-12-27 12:39:31
【问题描述】:

当我的 Node 应用程序启动时,它会尝试像这样连接到数据库:

var db = mongoose.connect('mongodb://what:ever.com:1234/database', function(err) {
    if(err) console.log('MongoDB: connection error -> ' + err);
    else console.log('MongoDB: successfully connected');
});

当它失败时,我得到一个完全符合我预期的错误,但我的 Node 应用程序终止了。连接返回错误时如何让节点应用继续运行?

有人可以指出 Mongoose 用于长期运行应用程序的最佳实践的方向吗?我知道 Mongoose 的重试连接标志默认设置为 true,但我还应该做什么?

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    嘿,有趣的是,你应该问这个问题。我几分钟前才写这个。 我正在使用咖啡脚本变体,但它看起来是这样的。我还在使用 colors.js 在控制台上提供漂亮的彩色反馈,但除此之外,这应该可以很好地捕获您的数据库错误而不会消失。

    让我先说我不是专家,我几周前才开始学习这个。

    mongoose = require "mongoose"
    db_address = "localhost/nodesample-dev"
    
    mongoose.connection.on "open", (ref) ->
      console.log "Connected to mongo server!".green
    
    mongoose.connection.on "error", (err) ->
      console.log "Could not connect to mongo server!".yellow
      console.log err.message.red
    
    try
      mongoose.connect("mongodb://#{db_address}")
      db = mongoose.connection
      console.log "Started connection on " + "mongodb://#{db_address}".cyan + ", waiting for it to open...".grey
    
    catch err
      console.log "Setting up failed to connect to #{db_address}".red, err.message
    

    这里是编译好的 JS:

    var db, db_address, mongoose;
    mongoose = require("mongoose");
    db_address = "localhost/nodesample-dev";
    
    mongoose.connection.on("open", function(ref) {
      return console.log("Connected to mongo server!".green);
    });
    
    mongoose.connection.on("error", function(err) {
      console.log("Could not connect to mongo server!".yellow);
      return console.log(err.message.red);
    });
    
    try {
      mongoose.connect("mongodb://" + db_address);
      db = mongoose.connection;
      console.log("Started connection on " + ("mongodb://" + db_address).cyan + ", waiting for it to open...".grey);
    } catch (err) {
      console.log(("Setting up failed to connect to " + db_address).red, err.message);
    }
    

    【讨论】:

    • 我已经完全复制了您的代码,但我的服务器仍然“崩溃”并出现以下错误:/node_modules/connect-mongo/lib/connect-mongo.js:141 throw new Error('Error connecting to database');
    • 看来是 connect-mongo 不是 mongoose 的问题
    • 我刚刚又检查了一遍。如果您正在运行香草猫鼬,我发布的代码可以正常工作。看起来它早些时候被绊倒了。您可能想尝试赶上您的 mongoStore。 connect-mongo documentation
    猜你喜欢
    • 2019-06-27
    • 2021-10-25
    • 2018-07-24
    • 1970-01-01
    • 1970-01-01
    • 2017-01-03
    • 1970-01-01
    • 2016-01-15
    • 1970-01-01
    相关资源
    最近更新 更多