我偶然发现了一个关于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,再试一次问题消失,一切正常,所以我想知道为什么?
答案 0 :(得分:3)
当较长时间运行的应用程序中的池连接返回connection closed
时,这是一个常见问题。
mongoose documentation建议将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');
});
答案 1 :(得分:1)
mongoose.connect()
不接受您在代码中使用的任何回调函数,即您的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);
});
所以,我建议你从这开始:
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(){})
我建议您仔细阅读这些quick start,mongoose docs - 如果在文档和文档中发现某些冲突,您可以了解如何跳转到源代码中。 mongodb/mongoose close connection