Serialization
Introduction
When you return a model from a route or write it to a log, it has to become plain JSON. Every model has a toJSON() method, so JSON.stringify(model), JSON.stringify([models]) and responses that serialize their body all work without extra code. You control what the JSON contains with three static properties: hidden, visible and appends. Loaded relations are included automatically.
For a response shape you design separately from the table, see API Resources.
The examples use these tables and models:
import { Schema, sqliteConnection } from '@plinthjs/database'
import { ConnectionDataSource, Model } from '@plinthjs/orm'
import type { CastType } from '@plinthjs/orm'
const db = sqliteConnection()
Model.connection = db
Model.dataSource = new ConnectionDataSource(db)
const schema = new Schema(db)
await schema.create('users', (table) => {
table.id()
table.string('name')
table.string('email')
table.string('password')
table.boolean('is_admin').default(false)
table.timestamps()
})
await schema.create('posts', (table) => {
table.id()
table.integer('user_id')
table.string('title')
table.string('internal_note').nullable()
table.timestamps()
})
class Post extends Model {
static override table = 'posts'
static override fillable = ['title', 'internal_note']
static override hidden = ['internal_note']
}
class User extends Model {
static override table = 'users'
static override fillable = ['name', 'email', 'password', 'is_admin']
static override hidden = ['password']
static override casts: Record<string, CastType> = { is_admin: 'boolean' }
static override appends = ['display_name']
static override relations = {
posts: (model: Model) => model.hasMany(Post, 'user_id'),
}
getDisplayNameAttribute(): string {
return `${this.getRawAttribute('name')} <${this.getRawAttribute('email')}>`
}
}Serializing Models
toJSON() returns a plain object. toObject() and toArray() are aliases.
const user = await User.create({
name: 'Ann',
email: 'ann@example.com',
password: 'secret',
is_admin: true,
})
user.toJSON()
// => {
// id: 1, name: 'Ann', email: 'ann@example.com', is_admin: true,
// created_at: '2026-...', updated_at: '2026-...',
// display_name: 'Ann <ann@example.com>',
// }
JSON.stringify(await User.all()) // an array of the same objectsCast values are serialized in their cast form: booleans are true or false, JSON columns are objects, and dates are ISO strings. See Mutators and Casts.
Hiding Attributes
List columns you never want in output in hidden. This is the place for password hashes, tokens and internal notes:
static override hidden = ['password']hidden only affects serialization. The attribute is still readable with getAttribute('password'), and still saved.
Allow-listing with visible
When visible is non-empty it is an allow-list: only those keys are serialized, and hidden is ignored.
class PublicUser extends User {
static override visible = ['id', 'name']
static override appends = []
}
PublicUser.hydrate({ id: 1, name: 'Ann', email: 'ann@example.com' }).toJSON()
// => { id: 1, name: 'Ann' }Use visible when a model has many columns and you want a small, explicit public surface. A new column then stays out of the output until you list it.
Appending Values
appends lists computed attributes to add to the output. Each name is read through getAttribute(), so it needs an accessor named get<StudlyName>Attribute. In the models above, display_name is produced by getDisplayNameAttribute().
Appended names go through the same visibility check as columns. With a visible list, include the appended name or it is dropped:
class Card extends User {
static override visible = ['id', 'display_name']
}Serializing Relationships
Relations that are loaded are added to the output under their relation name, and each related model is serialized with its own hidden, visible and appends. Relations that are not loaded are simply absent, which is why you decide what to include with with() or load().
const found = (await User.query().with('posts').first())!
JSON.stringify(found)
// => { "id": 1, ..., "posts": [{ "id": 1, "title": "Hi", ... }] }
// (the post's internal_note is hidden by Post)A loaded relation is left out when its name is in the parent's hidden list or hidden on the instance with makeHidden(). A visible allow-list lists columns, so it does not remove relations.
found.makeHidden('posts')
JSON.stringify(found) // no "posts" keyTIP
Serialization never triggers a query. The explicit loading model (see Relationships) guarantees that toJSON() only emits data you already fetched.
Serializing Dates
Models do not convert timestamp columns on their own. created_at and updated_at are stored as ISO 8601 strings, so they appear in that format. Add a date or datetime cast to your own date columns (for example verified_at): they are read as Date objects and serialize back to ISO strings. A model with no casts passes stored values through untouched.
Changing Visibility Per Instance
makeHidden() and makeVisible() change what one model instance serializes, without touching the class. Both accept names or arrays of names, apply to columns, appended attributes and relation names, and return the model:
const user = (await User.find(1))!
user.makeHidden('email').toJSON() // no email
user.makeVisible('password').toJSON() // password included, although the class hides itmakeVisible() also shows a column that a visible allow-list omits. The overrides live on the instance only; other instances and the class are unchanged.
Gotchas
- Accessors are applied to every stored column during serialization, with or without casts. A column with no accessor and no cast is written raw.
- For a response shape you design separately from the table, build it explicitly with an API resource, or define a subclass with different settings as
PublicUserdoes above.