In node.js, modules are cached after the first time they are loaded. So you don't need to pass the mongoose
from the app.js.
For example, in models/index.js:
require('./counters')
exports.User = require('./user')
require('./token');
require('./team');
require('./role');
require('./layer');
require('./feature');
// I prefer to use a loop to require all the js files in the folder.
in models/user.js:
var mongoose = require('mongoose');
var userSchema = mongoose.Schema({
// ... Define your schema here
});
var User = module.exports = mongoose.model('User', userSchema);
module.exports.getUserById = function(id, callback) {
User.findById(id, callback);
}
module.exports.getUserByUsername = function(username, callback) {
var query = {username: username};
User.findOne(query, callback);
}
in app.js:
var mongoose = require('mongoose');
var models = require('./models');
mongoose.connect(dbPath, function(err) {
if (err) throw err;
});
// Yes! You can use the model defined in the models/user.js directly
var UserModel = mongoose.model('User');
// Or, you can use it this way:
UserModel = models.User;
app.get('/', function(req, res) {
var user = new UserModel();
user.name = 'bob';
user.save();
// UserModel.getUserByUsername();
...
});
Learn more about the modules caching in node.js: http://nodejs.org/api/modules.html#modules_caching