Back to Objection Js

Overview

doc/api/model/overview.md

3.1.52.8 KB
Original Source

Overview

Model data lifecycle

For the purposes of this explanation, let’s define three data layouts:

  1. database: The data layout returned by the database.
  2. internal: The data layout of a model instance.
  3. external: The data layout after calling model.toJSON().

Whenever data is converted from one layout to another, converter methods are called:

  1. database -> $parseDatabaseJson -> internal
  2. internal -> $formatDatabaseJson -> database
  3. external -> $parseJson -> internal
  4. internal -> $formatJson -> external

So 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