Autoreconnect mongo create a lot of connections
Do you want to request a feature or report a bug? Bug What is the current behavior? When my server lost the connection with the database, when it is recovered, I have a lot of connection, the amount of connection is proportional to time.
I've detected this bug with mongoose, but it continuos when I use just mongodb. If the current behaviour is a bug, please provide the steps to reproduce.
- Open the database and execute: mongostat
- Wait the connection is established.
- Stop the connection (not the script)
- Restore the connection.
- Look the amount of connection created
var mongodb = require('mongodb').MongoClient; var Server = require('mongodb').Server; var url = 'mongodb://localhost:28410/myDatabase'; var options = { useNewUrlParser: true, autoReconnect: true, poolSize: 3, reconnectTries: Number.MAX_VALUE, reconnectInterval: 1000 } var conectDate = new Date(); var count = 0; // Connect to the db mongodb.connect(url, options, function (err, db) { if (!err) { console.log("We are connected"); db.on('close', function () { console.log('Close') }) db.on('reconnect', function () { console.log('Reconnect') }) } else { setTimeout(connectWithRetry, 1000); count++; console.log(conectDate + ' - Database not connected - ' + count); } });**Please mention your node.js, mongoose and MongoDB version.** I've detected this with node 6.1, 8.9.0 and 10.0.0. Mongoose versions: 5.1.2 MongoDb driver: 3.0.8 MongoServer: 3.2.13 and 3.4.13
What is the connectWithRetry() function, can you post that code as well?
Of course, but I've tested this with and without that function , and I've always had the problem.
var mongodb = require('mongodb').MongoClient;
var Server = require('mongodb').Server;
var url = 'mongodb://localhost:28410/edata';
var options = {
useNewUrlParser: true,
autoReconnect: true,
poolSize: 3,
reconnectTries: Number.MAX_VALUE,
reconnectInterval: 1000,
socketTimeoutMS: 5000
}
var conectDate = new Date();
var count = 0;
// Connect to the db
var connectWithRetry = function () {
mongodb.connect(url, options, function (err, db) {
if (!err) {
console.log("We are connected");
db.on('close', function () {
console.log('Close + ' + count);
})
db.on('reconnect', function () {
console.log('Reconnect')
})
}
else {
setTimeout(connectWithRetry, 1000);
count++;
console.log(conectDate + ' - Database not connected - ' + count);
}
});
}
connectWithRetry();
I believe I found the issue in the underlying driver and opened up a PR :point_up: . Will keep this open and track the issue.
Do you have new information?
@menme95 The above PR fixes this issue and will be released when the MongoDB driver ships v3.1.2, Mongoose will ship a release after that to fix this issue.
Can confirm this is fixed in master after we bumped mongodb driver -> 3.1.3