Defining document instance methods
Documents have their own built-in instance methods such as save
and remove
. However, we can write our own instance methods as well.
Documents are instances of models. They can be explicitly created:
const instance = new Model()
Or they can be the result of a query:
Model.findOne([conditions]).then((instance) => {})
Document instance methods are defined in the schema. All schemas have a method called method
which allows you to define custom instance methods.
Getting ready
In this recipe, you will define a schema and custom document instance methods for modifying and reading document properties. 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 this code:
npm...