如何使Mongoose连接正常失败

时间:2012-12-27 03:45:55

标签: node.js mongodb mongoose

当我的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,但我还应该做什么呢?

1 个答案:

答案 0 :(得分:7)

嘿,好笑,你应该问这个问题。我几分钟前就写这篇文章了。 我正在使用coffeescript变体,但它看起来如何。我也使用colors.js在控制台上获得了很好的彩色反馈,但除此之外,这应该很好地捕获你的db错误而不会消失。

让我先说我不是专家,几周前我刚开始接受这个。

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);
}