With the latest mongoose update, you can no longer user models the way I\'ve been doing. I need to share the same db connection across my entire app.
https://github.com/
My model code looks similar, but instead of repeatedly requiring the modules I just require them once when the application starts and then assign the results to a shared object. For example if you are using an express app you could just so something like app.locals.models.User = require('./models/user');
. Then anything with access to the app
can see your models without needing a require.
You can define your user module like so:
var mongoose = require('mongoose');
var userSchema = new mongoose.Schema({name: String});
var User = null;
module.exports = function(db) {
if (db && User === null) {
User = db.model('User', userSchema);
}
return User;
};
When you start your application you simply need to: require('./models/user')(db)
. Subsequent requires by other modules in your application can drop the db
paramater, as User
will only be set once.