Here is another way to accomplish this in less code.
UPDATE 3: Asynchronous model class statics
Similar to option 2, this allows you to create a function directly linked to the schema, but called from the same file using the model.
model.js
userSchema.statics.updateUser = function(user, cb) {
UserModel.find({name : user.name}).exec(function(err, docs) {
if (docs.length){
cb('Name exists already', null);
} else {
user.save(function(err) {
cb(err,user);
}
}
});
}
Call from file
var User = require('./path/to/model');
User.updateUser(user.name, function(err, user) {
if(err) {
var error = new Error('Already exists!');
error.status = 401;
return next(error);
}
});