Mongoose models are quite packed with both static and instance predefined methods, some of which you have already used. 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.
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 the 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 what is shown in the following code snippet:
UserSchema.statics.findOneByUsername = function(username, callback...