How to make mongoose connection available globally How to make mongoose connection available globally express express

How to make mongoose connection available globally


in your models folder create index.js

e.g.

    module.exports = function (mongoose,  dbconn) {        return {            modelname:  require("./file" )(mongoose, dbconn),            modelname2:  require("./file2" )(mongoose,  dbconn),   };};

then load it in your main startup file file where you create your db connection via

var models    = require("./models")(mongoose,dbconn);

the example model file in the models folder should look something like this:

module.exports = function (mongoose,  dbconn) {    /*     *      */    var schema = new mongoose.Schema({        /**         * field         * @type String         */        field: String......      });  return dbconn.model("modelname", schema, "collectioname");};

and so on....


I know it has been a while, but i have found this article and i was wondering what you guys think about it, it looks elegant.https://productbuilder.wordpress.com/2013/09/06/using-a-single-global-db-connection-in-node-js/

It basically say to use Node.js global.varName mechanism to share the connection globally.

BTW, i have tried it my self, and it worked seamlessly.


This sample project on GitHub is a brilliantly simple way to accomplish your goal. It's elegant and effective:https://github.com/fbeshears/register_models. The main code is:

(function(){  module.exports = function(){    var mongoose = require('mongoose');    var Schema = mongoose.Schema;     var files = ['kitten.js', 'comments.js'];    var fn = 0;            for(fn in files) {            var path_fn = "./" + files[fn];            var exported_model = require(path_fn);            exported_model(mongoose, Schema);        }    };})();

I make a dir called 'models' under my main app dir and put this in the folder and require it, then call register_models();