Sharing objects and avoiding globals in node.js

后端 未结 4 1901
眼角桃花
眼角桃花 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:39

    Try look at this way:

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

提交回复
热议问题