2017-02-11 96 views
0

我是新來表達/節點和一般的web編程。什麼是處理這個錯誤的最好方式,當貓鼬的MongoDB的連接超時,我這是怎麼連接:錯誤:連接超時 - expressjs mongodb mongoose

mongoose.connect(config.mongoUrl); 

const db = mongoose.connection; 
db.on('error', console.error.bind(console, 'error connecting with mongodb database:')); 
db.once('open', function() { 
    console.log('connected to mongodb database'); 
}); 

這是當它超時而我的服務器運行的錯誤:

錯誤連接與mongodb數據庫:錯誤:連接超時 在Db。 (C:\ Users \ Sean \ OneDrive \ webpages \ 000 \ lasttry \ node_modules \ mongoose \ lib \ drivers \ node-mongodb-native \ connection.js:169:17) at emitTwo(events.js:106:13) at Db.emit(events.js:191:7) at Server.listener(C:\ Users \ Sean \ OneDrive \ webpages \ 000 \ lasttry \ node_modules \ mongodb \ lib \ db.js:1798:14) 在服務器處的Server.emit(events.js:188:7) 處的emitOne(events.js:96:13) 處。 (events.js:96:13) (在服務器上.emit(事件)。)。(C:\ Users \ Sean \ OneDrive \ webpages \ 000 \ lasttry \ node_modules \ mongodb \ lib \ server.js:274:14) js:188:7) at Pool。 (C:\ Users \ Sean \ OneDrive \ webpages \ 000 \ lasttry \ node_modules \ mongodb-core \ lib \ topologies \ server.js:335:12) at emitOne(events.js:96:13) at Pool。在Connection處發射(events.js:188:7) 。 (C:\ Users \ Sean \ OneDrive \ webpages \ 000 \ lasttry \ node_modules \ mongodb-core \ lib \ connection \ pool.js:270:12) at Connection.g(events.js:291:16) at emitTwo(events.js:106:13) 在Connection.emit(events.js:191:7)

+0

什麼時候超時發生?如果節點進程通過我的計算機進入休眠狀態而被中斷,那麼我只有貓鼬超時。 – matt

+0

我正在使用mLab,它是一個雲MongoDB服務。它似乎隨機超時。我只見過它發生過兩次,但如果我去製作,它發生這將是一個噩夢哈哈。 – seanEd

+0

(請參閱文檔)[http://docs.mlab.com/timeouts/#connection-timeout]您需要設置一個連接超時值,就像在我發佈的答案中一樣。否則,如果連接有任何小問題,則不會在超時之前等待。 – matt

回答

4

如何關於斷開只是重新連接到MONGO。如下所示:

mongoose.connect(config.mongoUrl); 

var db = mongoose.connection; 
db.on('error', console.error.bind(console, 'error connecting with mongodb database:')); 

db.once('open', function() { 
    console.log('connected to mongodb database'); 
});  

db.on('disconnected', function() { 
    //Reconnect on timeout 
    mongoose.connect(config.mongoUrl); 
    db = mongoose.connection; 
}); 

您也可以在連接上設置超時值。

mongoose.connect(url, { server: { socketOptions: { connectTimeoutMS: 1000 }}}, function(err) { ... }); 

此外,請確保mongo仍在您的機器上運行。連接超時可能意味着mongo沒有運行。

參考:Another stack overflow question

0
  1. 檢查的mongod運行。

    在shell中輸入mongo

  2. 添加connectTimeoutMS=300000參數爲你uri。

    URI看起來像mongodb://localhost/collectionName?connectTimeoutMS=300000