Sharing objects and avoiding globals in node.js

后端 未结 4 1842
眼角桃花
眼角桃花 2021-02-03 15:03

What would be the most appropriate way of sharing the database connection in the below snippet ( the db variable) with my routers/controllers without turning the

4条回答
  •  孤独总比滥情好
    2021-02-03 15:28

    I ended up using Vadim Baryshev's answer and took it a bit further by creating a State module holding commonly used modules together, to keep things tidy:

    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);
    

    controllers/users.js:

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

提交回复
热议问题