1

I'm really confused with mongoose autoReconnect option inside mongoose.connect methods. My problem is that my server may start before database connection is ready, so I have to handle this at the start of my server code. Well, let me explain what I have until now:

First, I tried the documented way:

const db = mongoose.connection;
db.once('open', () => console.log('database connected'));
mongoose.connect(dbUri, { autoReconnect: true });

It kinda works, (mongo console shows: I NETWORK [listener] connection accepted from 127.0.0.1:52896 #1 (1 connection now open)) but it never calls the open callback. What is really weird about this solution though is that db.readyState never become 1 (which I suppose it's the reason the callback is never called).

After that, I searched for a solution and found several of them, including those here, and on github. To sum up them, here it is the basic solution:

function connect() {
    mongoose.connect(dbUri, { autoReconnect: true });
}

const db = mongoose.connection;

db.once('open', () => console.log('database connected'));

db.on('error', () => {
    console.log('database connection error');
    mongoose.disconnect();
});

db.on('disconnected', () => {
    console.log('database disconnected.');
    connect();
});

connect();

Again, this solution kida works too, but this time, every call to connect() method creates a new connection, so my mongo console show something like:

I NETWORK  [listener] connection accepted from 127.0.0.1:52896 #5 (35 connections now open)
I NETWORK  [listener] connection accepted from 127.0.0.1:52896 #6 (36 connections now open)
I NETWORK  [listener] connection accepted from 127.0.0.1:52896 #7 (37 connections now open)
...

Playing around I find out that's because of the autoReconnect option. If i set it to false (which is really not recommended by the documentation), a single connection is made when database is ready. But I think that autoReconnect means to do it not just when the connection is made, but while it's active through the execution of the application.

So, what am I missing here? Is there something that I should be doing in the first example? Do I keep autoReconnect and ignore the multiple connection thing? Or there is another solution I didn't find?

  • Node: 8.9.0
  • MongoDB: 3.6.5
  • Mongoose: 5.0.11
Kleber
  • 942
  • 1
  • 15
  • 25

0 Answers0