22

I'm using Mongoose to manage a Mongo database. My connection file is quite simple:

var mongoose = require('mongoose')

mongoose.connection.on("open", function(){
  console.log("Connection opened to mongodb at %s", config.db.uri)
});
console.log("Connecting to %s", config.db.uri)
mongoose.connect(config.db.uri)

global.mongoose = mongoose

Then in my app.js I just

require('./database)

and the "mongoose" variable is available globally. I'd prefer not to use globals (at least not directly). Is there a better way of sharing the database connection variable across node (I'm using express.js) via a singleton pattern or some other method?

typeoneerror
  • 55,990
  • 32
  • 132
  • 223
  • Mayby duplicate this http://stackoverflow.com/questions/9651066/how-can-i-structure-my-express-app-where-i-only-need-to-open-a-mongodb-connectio/9653519#9653519 – Vadim Baryshev Mar 13 '12 at 22:08

3 Answers3

29

I just do the following in my app.js file:

var mongoose = require('mongoose');
mongoose.connect('mongodb://address_to_host:port/db_name');
modelSchema = require('./models/yourmodelname').YourModelName;
mongoose.model('YourModelName', modelSchema);
// TODO: write the mongoose.model(...) command for any other models you have.

At this point any file that needs access to that model can do:

var mongoose = require('mongoose');
YourModelName = mongoose.model('YourModelName');

And finally in your model, you can have the file written normally then export it at the bottom:

module.exports.YourModelName = YourModelName;

I don't know if this the best most awesome solution (just started wrapping my head around exporting modules about 2 days ago) but it does work. Maybe someone can comment if this is a good way to do it.

Hot.PxL
  • 1,902
  • 1
  • 17
  • 30
AntelopeSalad
  • 1,736
  • 1
  • 16
  • 27
  • oh, ok, so I don't need a global variable pointing to "mongoose" because I can require it when I need it. – typeoneerror Mar 13 '12 at 20:06
  • Yep, also as far as I know express will cache modules you load. So once mongoose is loaded once, it's not like express will keep reloading it from scratch for each require. Would be cool if someone can confirm that for sure but I'm fairly sure I read that somewhere in the past. – AntelopeSalad Mar 13 '12 at 20:12
  • I don't know about express caching, but I know requires caches the modules it loads. – Joey Guerra Mar 23 '12 at 03:22
  • 3
    the code in the required module is executed only once. so you can require modules as many times as you want and the connection to mongo db for example will be created only once – Micha Roon Jan 21 '13 at 18:19
  • @AntelopeSalad Forgive me, as I'm a total newb here, but what would the `yourmodelname.js` file look like? Also, where does the missing right-paren go on line 3 of your first code sample? – Cory Klein Jun 27 '14 at 21:30
  • @CoryKlein, `yourmodelname.js` would have your database schema and any other mongoose related code you need in your model. Pretty sure the missing paren goes before `.YourModelName` but I haven't touched mongoose in like 2 years. It's either before or after `.YourModelName`. – AntelopeSalad Jul 03 '14 at 23:59
6

if you follow commonjs exports

exports.mongoose = mongoose

let us say your module name is connection.js

you can require

   var mongoose = require('connection.js')

you can use mongoose connection

Subba Rao
  • 10,576
  • 7
  • 29
  • 31
2

I generally wrap my models like this

var MySchema = (function(){
//Other schema stuff 

//Public methods
GetIdentifier = function() {
return Id;
};

GetSchema = function() {
return UserSchema;
};

return this;
})();

if (typeof module !== 'undefined' && module.exports) {
exports.Schema  = MySchema;
}

And in my main class, I do this var schema = require('./schema.js').Schema; and call conn.model(schema.GetIdentifier(), schema.GetSchema()) and of course after calling connect, or createConnection. This allows me to plugin schema in to standard set of methods. This generalization is good because you can concentrate on your schema after you have mastered connection and error handling. I also extend the schema with plugins, and that allows me to share plugins with other schemas.

I was looking to see if some body has done this better, but can't see to find a good pattern, and I am fairly new to Mongo.

I hope this helps.

Ovais Reza
  • 86
  • 4