Design pattern for shared database handle in Node.JS


How do I share a database connection across various NodeJS modules? The example I have found all had a monolithic structure where the entire code was in one single app.js file.

/* main.js */
var foo = require("./foo"); 
/* express stuff ...*/
mysql = /* establish mysql connection */ 
app.get("/foo", foo.hello ); 

/* foo.js */
exports.hello = function(req, res) {
   res.send("Hello from the foo module!"); 

How would I access "mysql" from my module "foo"? What is the recommended design pattern for this?

Problem courtesy of: user3033490


You can use the module pattern to easily pass your db object (and anything else) to modules that need it.

// users.js
module.exports = function( options ) {
    var db = options.db;
    var pants = options.pants;  // or whatever

    return {
        GetUser: function( userID, callback ) {
            db.query("....", function (err, results) {
        AnotherFunc: function (...) {},
        AndAnotherFunc: function (...) {}

You use this module like:

// make your db connection here

var users = require('./users.js')({
    db: db,
    pants: 'blue'

users.GetUser( 32, function( user ) {
    console.log("I got the user!");
    console.log( user );

I find this to be a great way to write modules, as it's a lot like making an actual Class object, like in C++. You can even simulate 'private' methods/parameters.

Solution courtesy of: Chris


I usually put mysql handle in a different file (module) and require the module in different routes.

I believe you also have to connect to mysql asynchronously, you can refer to this question, which uses a callback function to solve the problem.

Discussion courtesy of: Daiwei

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