我使用下面的代码在nodeJS中创建数据库连接。
var client = require('mongodb').MongoClient;
var dbase;
exports.dbconnection = function (uname,pwd,host,port,dbname,options) {
//If connection already exists return it
if (dbase !== undefined) return;
//If no db connection exists create one db connection and return it
if (!host) host = 'localhost';
if (!port) port = '27017';
if (!options) {
options = {
db:{w:1},
server: {poolSize: 10, socketOptions: {keepAlive:5000, connectTimeoutMS:30000}}
}
}
var dbstr;
if (!uname) dbstr = 'mongodb://'+host+':'+port+'/'+dbname;
else
dbstr = 'mongodb://'+uname+':'+pwd+'@'+host+':'+port+'/'+dbname;
client.connect(dbstr,options,function(err,db){
if (err) {
console.log('[SmartBin:dbclient:Server connection to the database server is failed, terminating application server....]');
process.exit(0);
}
dbase = db;
console.log('[SmartBin:dbclient:Connection to the database server is established successfully....]');
});
// If the node process ends, close the Mongoose connection
process.on('SIGINT', function() {
if (dbase) {
dbase.close(function () {
console.log('[SmartBin:dbclient:Application server has been shutdown....]');
process.exit(0);
});
}
});
};
exports.get = function(name,query,fields) {
return new Promise(function(resolve,reject){
var table = dbase.collection(name);
table.find(query,fields).toArray(function(err,result){
if (err) reject(err);
else
resolve(result);
});
});
};
我能够插入,从数据库中获取值,但一段时间后我得到拓扑销毁mongo错误消息。不在我关闭数据库连接的地方。拓扑被破坏的原因'可能是因为我试图在连接超时后插入。在我的应用程序中,数据库插入操作在6小时内发生一次,有时甚至更多。因此,如果我不查询数据库,将执行的唯一操作是插入操作。牢记这个场景,什么是connectionTimeout期间的最佳解决方案。我应该把它作为24小时或任何其他策略会更好。请建议。
我也不确定连接池是否在此示例中有效。每当我启动服务器节点时,我都会收到Warning: Possible EventEmitter memory leak detected. 11 SIGINT listeners added. Use emitter.setMaxListeners() to increase limit
消息。我试图从我的nodeJS应用程序中的11个不同的JS文件调用dbconnection方法。