当前位置 : 主页 > 网页制作 > Nodejs >

node.js – 如何使Mongoose连接正常失败

来源:互联网 收集:自由互联 发布时间:2021-06-16
当我的Node应用程序启动时,它会尝试连接到数据库,如下所示: var db = mongoose.connect('mongodb://what:ever.com:1234/database', function(err) { if(err) console.log('MongoDB: connection error - ' + err); else console.log
当我的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,但我还应该做什么呢?

嘿,好笑,你应该问这个问题.我几分钟前就写这篇文章了.
我正在使用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);
}
网友评论