1
votes

I have tried for a long time to solve this problem on my own but can't find a suitable fix for my problem.

I have this method:

handle_database = function(callback, req, res) {

pool.getConnection(function(err,connection){
    if (err) {
        res.json({"code" : 100, "status" : "Error in connection database"});
        return;
    }

    connection.query("select * from `atable`",function(err,rows){
        connection.release();
        if(!err) {
            callback(rows);
        }
    });

    connection.on('error', function(err) {
        res.json({"code" : 100, "status" : "Error in connection database"});
        return;
    });
});
}

This method is used in my routes.js in this way:

router.get('/', function(req, res){
    db.getUsers(function (data) {
        res.render('pages/index',{users: data, title: 'title'});
    }, req, res);

});

When I refresh this page 11 times in a row I get the following warning:

(node:11780) Warning: Possible EventEmitter memory leak detected. 11 error listeners added. Use emitter.setMaxListeners() to increase limit

But I cannot find how to fix this, or is just setting the limit to 0 a smart idea?

1
What are you using for connecting the DB and managing the pool ? - Denys Séguret
var pool = mysql.createPool({ connectionLimit : 10, host : 'localhost', user : 'root', password : 'pw', database : 'db', debug: false, }); - R4LPH
What plugin is that ? There are dozens of libraries to access databases in node. Do you use mysqljs/mysql ? - Denys Séguret
the plugin I use is: Mysql 2.12.0 - R4LPH

1 Answers

2
votes

You shouldn't add an error handler on the connection every time you want to issue a query. The connection is pooled, you don't get a new one every time. In your case it's a pool of size 10 and you reuse a connection on the eleventh call, that's when the warning is triggered.

Just check the error

  • on pool.getConnection
  • in connection.query

Here's how it could look:

handle_database = function(callback, req, res) {
    pool.getConnection(function(err,connection){
        if (err) {
            res.json({"code" : 100, "status" : "Error in connection database"});
            return;
        }

        connection.query("select * from `atable`",function(err,rows){
            connection.release();
            if(err) {
                res.json({"code" : whatever, "status" : "Error in querying database"});
                return;
            }
            callback(rows);

        });
    });
}