Creating a mongoose static method 'load' to be used by the main controller function for chaining and error handling.
UserSchema.load('54ae92dd8b8eef540eb3a66d')
.then(....)
.catch(....);
Encountered an issue with the ID being incorrect, prompting the need to catch this error. It is believed handling this in the model layer would be more efficient.
To ensure the controller catches the error, the following approach can be taken:
UserSchema.statics.load = function(id) {
if (!mongoose.Types.ObjectId.isValid(id)) {
return Promise.resolve().then(function() {
throw new Error('not a mongoose id');
});
}
return Promise.cast(this.findOne({
_id: id
}).exec());
};
Alternatively, when only following this approach, the error may not be successfully thrown into the controller's .catch function.
AchievementSchema.statics.load = function(id) {
if (!mongoose.Types.ObjectId.isValid(id)) {
throw new Error('not a mongoose id');
}
return Promise.cast(this.findOne({
_id: id
}).exec());
};
The question remains: am I approaching this correctly? If so, are there simpler ways to write the (*) statement? The current method seems cumbersome. Appreciate any input or suggestions. Thanks.