Defining static model methods
Models have built-in static methods such as find
, findOne
, and findOneAndRemove
. Mongoose allow us to define custom static model methods as well. Static model methods are defined in the schema in the same way as document instance methods are.
Schemas have a property called statics
which is an object. All the methods defined inside the statics
object are passed to the model. Static model methods can also be defined by calling the static
schema method.
Getting ready
In this recipe, you will define a schema and custom static model method for expanding your model's capabilities. First, ensure that you have MongoDB installed and it's running. As an alternative, if you prefer, a MongoDB DBaaS instance in the cloud will also do. Before you start, create a new package.json
file with the following code:
{ "dependencies": { "mongoose": "5.0.11" } }
Then, install the dependencies by opening a Terminal and running:
npm install
How to do it...
Define a static model...