In node.js, using mysql-simple-pool how do I share pool with all modules?


I am trying to get a db.js file that will basically hold 1 connection pool that all my other models which access a database can require and use.

My current code for db.js:

var Pool = require('mysql-simple-pool');

var mysql_pool = new Pool(50, {
    host: 'localhost',
    user: 'root',
    password: 'password',
    database: 'game'

//I used this line to try and init the pool, it didn't work :)
//mysql_pool.query("USE game", function(){});

exports = mysql_pool;

Then, in my model I say:

var pool = require('./models/db.js');

pool.query('select * from user where id = ', [user_id], function(err, rows) {

And I get the following error:

TypeError: Object #<Object> has no method 'query' at Strategy._verify 

Is there a better way? Is there a way to make this possible? :) Do I need to add more details?

Problem courtesy of: silkcom


Your problem is this:

exports = mysql_pool;

That should be:

module.exports = mysql_pool;

The reason for this is explained in this SO answer, but in short, you're basically doing this:

var module = { exports: {} };
var exports = module.exports;

exports = mysql_pool; // wrong! you're just reassigning the `exports` variable,
                      //        but that won't change `module.exports`

return module.exports;

After you require your module, module.exports is still the empty object, hence the error.

Solution courtesy of: robertklep


There is currently no discussion for this recipe.

This recipe can be found in it's original form on Stack Over Flow.