Sharing objects and excluding global variables in node.js

What would be the most suitable way to share the database connection in the fragment below (variable db) with my routers / controllers without turning the variable dbinto a global one?

var mongo = require('mongoskin'),
db = mongo.db(config.db.adress);

app.use(function(req, res, next) {
    db.open(function(err, data) {
        (err) ? res.send('Internal server error', 500) : next();
    });
});

// Setting up controllers here
app.post('/users', require('./controllers/users').create);

Based on the PHP background, I thought about Injection Dependency, but I have no idea if this fits in node.

+5
source share
4 answers

Try to look like this:

app.js:

var mongo = require('mongoskin'),
db = mongo.db(config.db.adress);

app.use(function(req, res, next) {
    db.open(function(err, data) {
        (err) ? res.send('Internal server error', 500) : next();
    });
});

require('./controllers/users')(app, db);

Controllers / users.js:

module.exports = function (app, db) {

    app.post('/users', function(req, res, next) {
        // Your create function
        // Link to db exists here
    });

};
+7
source

I have no experience with Mongoskin, but Mongoose has neatly sidestepped this issue by returning a Singleton Mongoose instance every time you require it.

( init) , , .

:

var mongoose = require('mongoose'),

  TodoSchema = new mongoose.Schema({
    title: { 'type': String, 'default': 'empty todo...' },
    order: { 'type': Number },
    done: { 'type': Boolean, 'default': false }
  });

mongoose.model('Todo', TodoSchema);

, :

  var mongoose = require('mongoose'),
      Todo = mongoose.model('Todo');

, Mongoose, , , .

mongoskin, , , , , db , :

db.js

exports.db = require('mongoskin').db('myProject-' + process.env.NODE_ENV);

:

var db = require('./db');

db.open(function(err, data) {
        (err) ? res.send('Internal server error', 500) : next();
    });

, db , , , .

+5

, State, , :

state.js:

module.exports = {
    mongo: require('mongoskin'),
    db: require('mongoskin').db('myProject-' +process.env.NODE_ENV )
} 

app.js:

var state = require('./state');
require('./controllers/Users')(app, state);

/users.js:

module.exports = function (app, state) {

    app.post('/users', function(req, res, next) {
        state.db.find({}, function(doc, err) {});
    });

};
+2

As @Jed Watson suggested, the moongoose module uses the singleton (anti?) Pattern, which is provided by the require / export mechanism. Here is a specific bit of code:

(like here: https://github.com/LearnBoost/mongoose/blob/master/lib/index.js )

/*!
 * The exports object is an instance of Mongoose.
 *
 * @api public
 */

var mongoose = module.exports = exports = new Mongoose;
0
source

All Articles