doc/api/model/overview.md
For the purposes of this explanation, let’s define three data layouts:
database: The data layout returned by the database.internal: The data layout of a model instance.external: The data layout after calling model.toJSON().Whenever data is converted from one layout to another, converter methods are called:
database -> $parseDatabaseJson -> internalinternal -> $formatDatabaseJson -> databaseexternal -> $parseJson -> internalinternal -> $formatJson -> externalSo for example when the results of a query are read from the database the data goes through the $parseDatabaseJson method. When data is written to database it goes through the $formatDatabaseJson method.
Similarly when you give data for a query (for example query().insert(req.body)) or create a model explicitly using Model.fromJson(obj) the $parseJson method is invoked. When you call model.toJSON() or model.$toJson() the $formatJson is called.
Note: Most libraries like express and koa automatically call the toJSON method when you pass the model instance to methods like response.json(model). You rarely need to call toJSON() or $toJson() explicitly.
By overriding the lifecycle methods, you can have different layouts for the data in database and when exposed to the outside world.
All instance methods of models are prefixed with $ letter so that they won’t overlap with database properties. All properties that start with $ are also removed from database and external layouts.
In addition to these data formatting hooks, Model also has query lifecycle hooks