当我的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,但我还应该做什么呢?
答案 0 :(得分:7)
让我先说我不是专家,几周前我刚开始接受这个。
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);
}