mongoose输出错误“错误:连接closures”

我偶然发现了一个关于mongoose连接mongodb的好奇问题,它产生了如下的细节错误

e:\Mentor_Resources\node\node_twitter_bootstrap>node app Express server listening on port 3000 Trace: error occure when start to connect dbError: connection closed at e:\Mentor_Resources\node\node_twitter_bootstrap\server\module\word.js:14: 17 at Connection.open (e:\Mentor_Resources\node\node_twitter_bootstrap\node_mod ules\mongoose\lib\connection.js:201:5) at Db.open (e:\Mentor_Resources\node\node_twitter_bootstrap\node_modules\mon goose\node_modules\mongodb\lib\mongodb\db.js:247:16) at Server.connect.connectionPool.on.server._serverState (e:\Mentor_Resources \node\node_twitter_bootstrap\node_modules\mongoose\node_modules\mongodb\lib\mong odb\connection\server.js:413:7) at EventEmitter.emit (events.js:115:20) at connection.on.connectionStatus (e:\Mentor_Resources\node\node_twitter_boo tstrap\node_modules\mongoose\node_modules\mongodb\lib\mongodb\connection\connect ion_pool.js:108:15) at EventEmitter.emit (events.js:91:17) at Socket.closeHandler (e:\Mentor_Resources\node\node_twitter_bootstrap\node _modules\mongoose\node_modules\mongodb\lib\mongodb\connection\connection.js:401: 12) at Socket.EventEmitter.emit (events.js:88:17) at Socket._destroy.destroyed (net.js:364:10) 

mongoose的代码片段是:

 var mongoose = require('mongoose'); mongoose.connect("mongodb://localhost/word-sentence",function(err) { if(err) console.trace('error occure when start to connect db' + err); }); 

我确信mongodb是开放的,我重新启动mongodb几次,但错误仍然存​​在,所以我重新启动我的Windows XP,并再次尝试问题消失,一切都好,所以我想知道为什么?

当长时间运行的应用程序中的联合connection closed返回connection closed时,这是一个常见问题。

mongoose文档build议添加keepAlive到您传递给connect函数的选项对象。

这是一个例子(如果你不使用这个,你可以删除replset

 // include keep alive for closing connections, // http://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html var mongoOptions = { db: {safe: true}, server: { socketOptions: { keepAlive: 1 } }, replset: { rs_name: 'myReplSet', socketOptions: { keepAlive: 1 } } }; mongoose.connect( YOUR_URI, mongoOptions ); mongoose.connection.on('error', function(err) { console.log('Mongo Error:\n'); console.log(err); }).on('open', function() { console.log('Connection opened'); }); 

mongoose.connect()不接受任何callback函数,就像你在你的代码中使用的那样,你的代码片段是mongoose:

 var mongoose = require('mongoose'); mongoose.connect("mongodb://localhost/word-sentence",function(err) { if(err) console.trace('error occurred, when attempted to connect db. Error: ' + err); }); 

所以,我build议你从这开始:

 var mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/word-sentence'); var db = mongoose.connection; db.on('error', console.error.bind(console, 'connection error:')); db.once('open', function callback () { // yay connected! }); 

再次,你不能指望从db.open('open', function cb(){})callbackdb.open('open', function cb(){})任何参数

我build议通过这些快速 入门 , mongoose文档 – 启发如何在文档和mongodb / mongooseclosures连接中发现一些冲突时跳转到源代码