title: Handling Mongoose Disconnect
body: <p>I am using mongoose 4.13.7</p>
  
  <p>I want to connect to mongo but if an error occurs I want to reconnect. 
  But after 5 reconnects, if an error occurs, the process should exit.</p>
  
  <p>This is the code:</p>
  
  <pre><code>var count = 0;
  handleDisconnect();
  function handleDisconnect(){
      count++;
      console.log('Trying to connect to mongo. Attempt : ' + count);
      mongoose.connect(config.mongo.uri,{useMongoClient:true});
      mongoose.connection.on('error',(error)=&gt;{
          if (count &gt;= 5){
              console.log('Mongo ERROR');
              console.error(error);
              process.exit(1);
          }
          else{
              setTimeout(handleDisconnect,1000);  
          }
      });
      mongoose.connection.on('open',()=&gt;{
          console.log('Connected to mongo at ' + Date.now());
      });
  }
  </code></pre>
  
  <p>I have posted the output of the code as well. I don't understand how the attempt count is exceeding 5? There is also a memory leak warning and node:6804 error message. What am I doing wrong?</p>
  
  <p><a href="https://i.stack.imgur.com/aUdXL.png" rel="nofollow noreferrer">Output of the code</a></p>