2012-12-27 31 views
3

當我節點應用程序啓動時,它會嘗試連接到數據庫,像這樣:如何讓貓鼬連接失敗擺好

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,但我還應該做些什麼?

回答

6

嘿有趣的你應該問這個問題。我幾分鐘前就寫了這個。 我正在使用一個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); 
} 
+0

我複製完全相同的代碼和我的服務器仍然是「崩潰」,出現以下錯誤:'/ node_modules /連接 - 蒙戈/ lib目錄/連接-mongo.js:141 拋出新的錯誤('錯誤連接到數據庫');' –

+0

它看起來像這是一個連接問題mongo不mongoose – thepk

+0

我剛剛再次檢查。我發佈的代碼工作正常,如果你正在運行香草貓鼬。它看起來像早些時候被絆倒了。你可能想嘗試捕捉yor mongoStore。 [connect-mongo文檔](https://github.com/kcbanner/connect-mongo) – thepk