Sharing objects and avoiding globals in node.js

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

    I don't have any experience with mongoskin but Mongoose neatly sidesteps this problem by returning a Singleton instance of Mongoose every time you require it.

    Which allows you to create a connection once (on app init, usually) and simply use it by querying Models when you need it.

    It also allows you to define your models once like this:

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

    And then use them wherever you need to like this:

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

    More information on how Mongoose works like this, with example code can be found in this answer here.

    From mongoskin's docs, it looks like you have to connect each time you want to use it, which you could simplify by wrapping the db connection in a file you can require:

    db.js

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

    use it:

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

    The method above, where db is passed as an argument to every function that may need it, leads to callback soup and should be avoided if possible.

提交回复
热议问题