Node.js 如何使猫鼬连接正常失败

Node.js 如何使猫鼬连接正常失败,node.js,mongodb,mongoose,Node.js,Mongodb,Mongoose,当我的节点应用程序启动时,它会尝试连接到数据库,如下所示: 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'); }); 当它失败时,我会

当我的节点应用程序启动时,它会尝试连接到数据库,如下所示:

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');
});
当它失败时,我会得到一个与预期完全相同的错误,但我的节点应用程序会终止。当连接返回错误时,如何让节点应用程序继续运行


有人能告诉我Mongoose针对长期运行应用程序的最佳实践的方向吗?我知道Mongoose的重试连接标志默认设置为true,但我还应该做什么呢?

嘿,有趣的是,你应该问这个问题。我不是几分钟前才写的。 我使用的是coffeescript变体,但它看起来是这样的。我还使用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\u modules/connect mongo/lib/connect mongo.js:141抛出新错误(“连接到数据库时出错”)看起来是连接mongo而不是Mongoose的问题。我刚刚再次检查。如果你运行的是香草猫鼬,我发布的代码可以正常工作。看起来它在早些时候被绊倒了。你可能想抓住你的蒙哥斯托尔。