节点js群集mongoose连接

我在我的应用程序mongodb(不分片)中使用集群模块中构build的nodejs,用于存储每个集群(worker)连接时使用mongoose.createConnection方法,并在插入数据后closures。

但是我期望的是每当一个请求被打开的时候它打开连接到数据库和进程请求并closures连接。

但是我注意到当我检查mongodb日志仍然打开连接,并且它的计数比没有处理器/(群集节点)更大。

我把poolSize:1,autreconect:false仍然有一些连接即使在调用close()方法后也不会closures。

我的意见是当连接错误发生连接没有closures请帮助我

我正在使用以下脚本来获取连接。

module.exports.getDb = function () { var dburl = 'mongodb://localhost/DB'; db = mongoose.createConnection(dburl, { server: { socketOptions: { keepAlive: 1, connectTimeoutMS: 30000 }, auto_reconnect: false, poolSize: 1 } }, function (err) { console.log(err) }); db.on('error', function (err) { console.log(err + " this is error"); db.close(); }); return db; } 

并在evey查询callback结束时使用db.close()closures连接。

你在找这样的东西吗?

 db.connection.on('error', function (e) { console.log(e + " this is error"); db.close(); }); 

对于我的API服务器,我为Hapi写了一个插件来处理这个问题。 看看,它可能会帮助你。

 'use strict'; var bluebird = require('bluebird'); var mongoose = bluebird.promisifyAll(require('mongoose')); exports.register = function(plugin, options, next) { mongoose.connect(options.mongo.uri, options.mongo.options, function (e) { if (e) { plugin.log(['error', 'database', 'mongodb'], 'Unable to connect to MongoDB: ' + e.message); process.exit(); } mongoose.connection.once('open', function () { plugin.log(['info', 'database', 'mongodb'], 'Connected to MongoDB @ ' + options.mongo.uri); }); mongoose.connection.on('connected', function () { plugin.log(['info', 'database', 'mongodb'], 'Connected to MongoDB @ ' + options.mongo.uri); }); mongoose.connection.on('error', function (e) { plugin.log(['error', 'database', 'mongodb'], 'MongoDB ' + e.message); }); mongoose.connection.on('disconnected', function () { plugin.log(['warn', 'database', 'mongodb'], 'MongoDB was disconnected'); }); }); return next(); }; exports.register.attributes = { name: 'mongoose', version: '1.0.0' };