Using a connection pool without database

suggest change

Achieving multitenancy on database server with multiple databases hosted on it.

One pool per database is unnecessary when the databases are on the same server. Create the pool against the server and switch the database on the connection you check out.

Suppose our application has different databases for each firm hosted on database server. We will connect to respective firm database when user hits the application. here is the example on how to do that:-

var pool  = mysql.createPool({
      connectionLimit : 10,
      host            : 'example.org',
      user            : 'bobby',
      password        : 'pass'
    });
    
pool.getConnection(function(err, connection){
    if(err){
        return cb(err);
    }
    connection.changeUser({database : "firm1"}, function (err) {
        if (err) {
            connection.release();
            return cb(err);
        }
        connection.query("SELECT * from history", function(err, data){
            connection.release();
            cb(err, data);
        });
    });
});

Let me break down the example:-

The pool configuration names the server and not a database:

{
  connectionLimit : 10,
  host            : 'example.org',
  user            : 'bobby',
  password        : 'pass'
}

so when we want to use the specific database on database server, we ask the connection to hit database by using:-

connection.changeUser({database : "firm1"});

you can refer the official documentation here

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents