Search code examples
mysqlnode.jsmysql-connectorloopback

Node creates new mysql connections on parallel executions, and doesn't end the new connections


I'm trying to write a program using loopback - node - mysql wherein parallel DB(MySQL) calls are made. There is already a persistent connection between node and MySQL. When the parallel calls are made, additional connections to MySQL DB are created to fulfill the request. But on completion of the parallel calls and function, the new connections made to MySQL still persist. So on the long run a lot of connections are made to MySQL DB which aren't closed after use.
Here is My Code

function getSubTypeIdAndOrderForNewTimelineStory(gameId, name) {
  var deferred = $q.defer();
  async.parallel([
  function (callback) {
    getTimelineStorySubType(name).then(function (timelineStorySubType) {
      callback(null, timelineStorySubType.id);
    }).fail(function (error) {
      callback(error);
    });
  },
function (callback) {
  getLastTimeLineStory(gameId).then(function (gameTimelineStory) {
    callback(null, gameTimelineStory? gameTimelineStory.order+1: 1);
  }).fail(function (error) {
     callback(error);
  });
 }
], function (error, result) {
  if(error){
  deferred.reject(error);
}
else {
  var response = {
    gameTimelineStorySubTypeId : result[0],
    order : result[1]
  }
  deferred.resolve(response);
 }
});
return deferred.promise;
}

So either i need to know the number of existing unused connections or set a timeOut in mysql to terminate unused connections.
Thanks


Solution

  • In the dataSource object you can find free connections which needs to be removed from the pool.

    function removeOpenDatabaseConnections(dataSource){
     var freeConections = dataSource.connector.client._freeConnections;
     freeConections.forEach(function (freeConnection) {
      freeConnection._removeFromPool();
     }); 
    }