Movatterモバイル変換


[0]ホーム

URL:


Objection.js

# 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 examplequery().insert(req.body)) or create a model explicitly usingModel.fromJson(obj) the$parseJson method is invoked. When you callmodel.toJSON() ormodel.$toJson() the$formatJson is called.

Note: Most libraries likeexpress(opens new window) andkoa(opens new window) automatically call thetoJSON method when you pass the model instance to methods likeresponse.json(model). You rarely need to calltoJSON() 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 fromdatabase andexternal layouts.

In addition to these data formatting hooks, Model also has query lifecycle hooks

Static Properties


[8]ページ先頭

©2009-2025 Movatter.jp