Getting Started
Introduction
@plinthjs/orm is an active-record ORM. Each database table has a model class, and every instance of that class is one row. Models let you read, create, update and delete rows without writing SQL, track which attributes changed, soft delete, scope queries, and load related models without N+1 queries.
The ORM sits on top of @plinthjs/database: it reads and writes through a database Connection, and the examples on this page create their tables with the Schema builder from that package. Every example here runs against an in-memory SQLite database.
pnpm add @plinthjs/orm @plinthjs/databaseINFO
Relationships are explicit and async. There is no hidden lazy loading, because Node cannot block on I/O inside a property getter. You load relations up front with with(), onto an existing model with load(), or query them with related(). This is covered in Relationships.
Defining Models
A model is a class that extends Model and names its table. Columns are not declared on the class: the model reads whatever columns the row has.
import { Schema, sqliteConnection } from '@plinthjs/database'
import { ConnectionDataSource, Model } from '@plinthjs/orm'
class User extends Model {
static override table = 'users'
static override fillable = ['name', 'email', 'active', 'votes']
}The static properties below configure a model. All of them have defaults, so a model only needs table.
| Property | Default | Purpose |
|---|---|---|
table | '' | The table the model reads and writes. |
primaryKey | 'id' | The primary key column. |
timestamps | true | Maintain created_at and updated_at. |
createdAtColumn, updatedAtColumn | 'created_at', 'updated_at' | Rename the timestamp columns. |
fillable, guarded | [], ['*'] | Mass assignment rules. |
softDeletes, deletedAtColumn | false, 'deleted_at' | Soft delete support. |
casts, hidden, visible, appends | {}, [], [], [] | See Mutators and Casts and Serialization. |
relations | {} | See Relationships. |
Attributes are read with getAttribute() and written with setAttribute(). There are no generated property accessors for columns, so user.name is undefined; use user.getAttribute('name').
Primary keys and timestamps
By default the primary key is id and the model stamps created_at and updated_at (as ISO 8601 strings) when it inserts or updates. Turn this off with timestamps = false, or rename the columns:
class AuditLog extends Model {
static override table = 'audit_logs'
static override primaryKey = 'uuid'
static override timestamps = false
}
class Legacy extends Model {
static override table = 'legacy'
static override createdAtColumn = 'made_at'
static override updatedAtColumn = 'changed_at'
}For tests, replace the clock by overriding static now = () => new Date('2026-01-01T00:00:00Z').
Mass assignment
new User({ ... }), fill(), update() and create() only assign attributes that are mass assignable. There are two ways to say which:
fillableis an allow-list. When it is non-empty, only those columns can be mass assigned.guardedis a deny-list used whenfillableis empty. The default['*']guards everything, so a model with neither property set cannot be mass assigned at all.
class Thing extends Model {
static override table = 'things'
static override guarded = ['secret'] // everything except `secret` is fillable
}
const thing = new Thing({ name: 'a', secret: 'x' })
thing.getAttribute('name') // => 'a'
thing.getAttribute('secret') // => undefined (silently ignored)
thing.forceFill({ secret: 'x' }) // bypasses the guardAttributes that are not fillable are dropped without an error. Use forceFill() when you set values from trusted code.
Connecting a Model to a Database
A model needs a database connection, which you set once at startup:
const db = sqliteConnection() // in memory; pass { filename: 'app.db' } for a file
Model.connection = dbThat one assignment is enough. The ORM has two query paths, and both are derived from the connection:
- The active-record API (
Model.all(),find(),where(),newQuery(),create(),save(),update(),delete(), soft deletes, scopes, chunking, upserts and events) usesModel.connectiondirectly. - The relationship API (
Model.query(),with(),load(),related()and the relationship aggregates) reads throughModel.dataSource. When you do not set it, aConnectionDataSourceoverModel.connectionis created for you.
Set Model.dataSource only to override that, for example with the in-memory ArrayDataSource in fast tests, or with a ConnectionDataSource over a different connection:
Model.dataSource = new ConnectionDataSource(db) // optional; same as the defaultIf connection is missing, active-record calls throw Model [User] has no connection. Set static connection.... If neither dataSource nor connection is set, User.query() throws Model [User] has no data source. Set Model.connection ... or set Model.dataSource to a ConnectionDataSource.
Both are static properties, so setting them on Model applies to every model. A subclass can assign its own (for example Report.connection = analyticsDb) to use a different connection.
The examples on this page use this table:
const schema = new Schema(db)
await schema.create('users', (table) => {
table.id()
table.string('name')
table.string('email').unique()
table.boolean('active').default(true)
table.integer('votes').default(0)
table.timestamps()
})Retrieving Models
Model.all() returns every row as a model instance, find() looks one up by primary key, and first() returns the first row:
await User.create({ name: 'Ann', email: 'ann@example.com', votes: 3 })
await User.create({ name: 'Bob', email: 'bob@example.com', votes: 9 })
const users = await User.all()
users.length // => 2
const bob = await User.find(2)
bob?.getAttribute('name') // => 'Bob'
await User.find(99) // => null
const first = await User.first()Building queries
Model.where() starts a query. The builder supports the fluent surface of the database query builder (where, orWhere, whereIn, whereNull, whereBetween, orderBy, latest, oldest, limit, offset, forPage and more) and its terminal methods get() and first() return hydrated models.
const voters = await User.where('active', true)
.where('votes', '>', 2)
.orderBy('votes', 'desc')
.get()
voters.map((user) => user.getAttribute('name')) // => ['Bob', 'Ann']
await User.where('name', 'like', 'A%').first()
await User.newQuery().whereIn('id', [1, 2]).orderByDesc('id').limit(5).get()Model.newQuery() returns the same builder with no constraints. getQuery() gives you the underlying database query builder when you need something the model builder does not wrap.
Not found errors
findOrFail() throws a ModelNotFoundError when no row matches. This is the error to catch in a route handler to return a 404.
import { ModelNotFoundError } from '@plinthjs/orm'
try {
await User.findOrFail(99)
} catch (error) {
error instanceof ModelNotFoundError // => true
;(error as Error).message // => 'No query results for model [User] 99.'
}firstOrFail() does the same for the first row of a query, on both Model.where(...) builders and Model.query():
const user = await User.where('email', 'nobody@example.com').firstOrFail()
// throws ModelNotFoundError: No query results for model [User].Pagination
paginate(page, perPage) and simplePaginate(page, perPage) return paginators whose items are models. They exist on the model and on every builder, and respect scopes, soft deletes and eager loads:
const page = await User.where('active', true).orderBy('id').paginate(2, 15, { path: '/users' })
page.items() // => User instances
page.total() // => the total number of matching rows
page.nextPageUrl() // => '/users?page=3'See Pagination for the paginator API and the path, pageName and query options.
Chunking and streaming
To process many rows without loading them all, page through them with chunk(), run a callback per model with each(), or iterate with cursor() (or its alias lazy()), which pages in the background and yields one model at a time.
await User.chunk(100, (models) => {
// called with up to 100 models at a time
})
await User.each((user, index) => {
// called once per model
})
for await (const user of User.cursor(250)) {
user.getAttribute('email')
}Returning false from a chunk() or each() callback stops iteration. The same methods exist on a constrained builder, for example User.where('active', true).chunk(100, fn).
Aggregates
The model builder has count() and exists(). For sum, avg, min and max, call getQuery() to reach the database builder:
await User.where('votes', '>', 3).count() // => 1
await User.where('votes', '>', 3).exists() // => true
await User.newQuery().getQuery().sum('votes') // => 12
await User.newQuery().getQuery().max('votes') // => 9For counts and sums over a relationship, see Relationship Aggregates.
Inserting and Updating Models
Creating
create() fills a new model, saves it, and returns it with its generated primary key:
const user = await User.create({ name: 'Cy', email: 'cy@example.com' })
user.getKey() // => 3
user.exists // => trueYou can also build a model first and save it later. save() inserts when the model does not exist yet:
const draft = new User({ name: 'Dee', email: 'dee@example.com' })
draft.exists // => false
await draft.save()
draft.exists // => trueAfter an insert, the model holds only the attributes it was given plus the key and timestamps. Columns that the database defaulted (such as active) are not loaded until you call refresh().
Updating
Change attributes, then save(). Only the dirty columns are written, and updated_at is refreshed:
const ann = (await User.find(1))!
ann.setAttribute('name', 'Ann Lee')
await ann.save()
await ann.update({ votes: 10 }) // fill() + save() in one callTo update many rows in one statement, use the builder. It returns the affected row count and does not fire model events:
await User.where('active', false).update({ votes: 0 }) // => number of rowsDirty tracking
A model remembers the values it was loaded or last saved with. isDirty() and getDirty() tell you what has changed since:
const user = (await User.find(1))!
user.isDirty() // => false
user.setAttribute('name', 'Changed')
user.isDirty() // => true
user.isDirty('email') // => false
user.getDirty() // => { name: 'Changed' }
await user.save()
user.isDirty() // => falsefresh() returns a new copy loaded from the database, and refresh() reloads the current instance in place, discarding unsaved changes and loaded relations.
Replicating and touching
replicate() returns an unsaved copy without the primary key and timestamps. Pass column names to leave out as well:
const copy = ann.replicate(['email'])
copy.setAttribute('email', 'copy@example.com')
copy.exists // => false
await copy.save()touch() updates only updated_at, and fires updating and updated with the timestamp as the dirty attribute. It returns false when timestamps are off, the model does not exist yet, or an updating listener cancels it.
await ann.touch() // => trueFirst or create, update or create
These helpers look a row up by one set of attributes and fall back to a second set:
// Find by email, or create with these values. Returns the existing row untouched.
const user = await User.firstOrCreate({ email: 'new@example.com' }, { name: 'New' })
// Like firstOrCreate, but not saved.
const unsaved = await User.firstOrNew({ email: 'maybe@example.com' }, { name: 'Maybe' })
unsaved.exists // => false
// Find by email and apply the values, or create. Always leaves the row with the values.
const synced = await User.updateOrCreate({ email: 'new@example.com' }, { name: 'Renamed' })Upserting in bulk
upsert() inserts many rows in one statement and updates the rows that conflict on a unique column. The conflict columns must have a unique index, which is why email is unique() in the table above. It returns the affected row count.
await User.upsert(
[
{ email: 'ann@example.com', name: 'Ann Updated' },
{ email: 'zed@example.com', name: 'Zed' },
],
'email', // the unique column (or an array of columns)
['name'], // columns to update on conflict; defaults to every other column
)When timestamps are on, created_at and updated_at are stamped on every row, and updated_at is refreshed on conflict.
Deleting Models
delete() removes the row and returns true. A model that does not exist yet returns false.
const cy = (await User.find(3))!
await cy.delete() // => true
cy.exists // => false
await User.where('votes', 0).delete() // bulk delete, returns the row count (fires no events)Soft Deleting
With softDeletes = true, delete() sets the deleted_at column instead of removing the row, and queries skip trashed rows by default. The table needs a nullable deleted_at column, which table.softDeletes() adds.
await schema.create('flights', (table) => {
table.id()
table.string('name')
table.integer('seats').default(0)
table.timestamps()
table.softDeletes()
})
class Flight extends Model {
static override table = 'flights'
static override fillable = ['name', 'seats']
static override softDeletes = true
}
const flight = await Flight.create({ name: 'LH400', seats: 120 })
await flight.delete()
flight.trashed() // => true
await Flight.all() // => [] (trashed rows are excluded)
await Flight.withTrashed().get() // includes the trashed row
await Flight.onlyTrashed().get() // only trashed rows
await flight.restore() // clears deleted_at
await flight.forceDelete() // really removes the rowwithTrashed() and onlyTrashed() are available on the model and on any builder, so Flight.where('seats', '>', 100).withTrashed() works. find() skips trashed rows too; fresh() and refresh() include them.
A bulk builder.delete() on a soft deleting model also sets deleted_at (and updated_at) instead of deleting. Use forceDelete() on the builder for a real DELETE:
await Flight.where('seats', 0).delete() // soft deletes every matching flight
await Flight.onlyTrashed().forceDelete() // really removes the trashed onesThe soft delete filter applies on every read path: Model.newQuery(), Model.query(), relations loaded with with() or load(), related(), withCount() and the other relationship aggregates. Call withTrashed() or onlyTrashed() on the builder to change it, including inside an eager constraint:
await User.query()
.with({ flights: (query) => query.withTrashed() })
.get()Query Scopes
Global scopes
A global scope is a function added to the globalScopes array. It receives the builder and runs for every query on the model, just before execution:
import type { ModelBuilder } from '@plinthjs/orm'
class ActiveUser extends Model {
static override table = 'users'
static override globalScopes = [
(query: ModelBuilder<Model>) => {
query.where('active', true)
},
]
}
await ActiveUser.all() // only active usersSoft deletes are applied separately and do not need an entry here.
Local scopes
A local scope is a named function in the scopes map. Call it with scope(name, ...args), either on the model or on a builder, which makes scopes chainable:
class Post extends Model {
static override table = 'posts'
static override scopes = {
popular: (query: ModelBuilder<Model>) => {
query.where('votes', '>', 100)
},
ofAuthor: (query: ModelBuilder<Model>, authorId: unknown) => {
query.where('user_id', authorId as number)
},
}
}
await Post.scope('popular').get()
await Post.scope('popular').scope('ofAuthor', 1).orderBy('votes', 'desc').get()Calling a scope that is not defined throws Scope [name] is not defined on [Post].
Pruning Models
Pruning deletes stale rows in bulk. Override the static prunable() method to return a query for the rows that can go, then call pruneAll(). It deletes in chunks, one model at a time, so soft deletes and model events still apply, and returns the number removed.
class Session extends Model {
static override table = 'sessions'
static override timestamps = false
static override prunable() {
const cutoff = new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString()
return this.newQuery().where('last_seen_at', '<', cutoff) as unknown as ModelBuilder<Model>
}
}
const removed = await Session.pruneAll() // => number of deleted rowsThe default prunable() matches nothing, so pruneAll() is a no-op until you override it. Run it from a scheduled task (see Scheduling).
Events
Models fire events as they are saved and deleted, and a listener can cancel the operation. See Events.