Defining custom model methods
Mongoose models are pretty packed with both static and instance predefined methods, some of which you already used before. However, Mongoose also lets you define your own custom methods to empower your models, giving you a modular tool to separate your application logic properly. Let's go over the proper way of defining these methods.
Defining custom static methods
Model static methods give you the liberty to perform model-level operations, such as adding extra find
methods. For instance, let's say you want to search users by their username. You could of course define this method in your controller, but that wouldn't be the right place for it. What you're looking for is a static model method. To add a static method, you will need to declare it as a member of your schema's statics
property. In our case, adding a findOneByUsername()
method would look like the following code snippet:
UserSchema.statics.findOneByUsername = function (username, callback) { this.findOne...