( This is copy and pasted entirely from https://thecodebarbarian.wordpress.com/2013/06/06/61/comment-page-1/#comment-1215 )
// GOOD
exports.listUsers = function(User) {
return function(req, res) {
User.find({}, function(error, users) {
res.render('list_users', { users : users });
});
}
};
// BAD
var db = Mongoose.createConnection('localhost', 'database');
var Schema = require('../models/User.js').UserSchema;
var User = db.model('users', Schema);
exports.listUsers = return function(req, res) {
User.find({}, function(error, users) {
res.render('list_users', { users : users });
});
};
The biggest problem with the “bad” version of listUsers shown above is that if you declare your model at the top of this particular file, you have to define it in every file where you use the User model. This leads to a lot of error-prone find-and-replace work for you, the programmer, whenever you want to do something like rename the Schema or change the collection name that underlies the User model.
In addition, note that the “bad” listUsers is impossible to unit test. The User schema in the “bad” example is inaccessible through calls to require, so we can’t mock it out for testing.