API Reference

Objection.js

SQL-friendly ORM built on Knex that adds relation mapping, eager loading, and a powerful query builder for Node.js.

Official Documentation ↗
CompatibilityThis documentation covers version v3. Check the official docs for the latest API surface.

Installation

npmnpm install objection knex
pnpmpnpm add objection knex

Methods

Overview

Objection.js is a SQL-friendly ORM built on Knex that adds relation mapping, eager loading, and a rich query builder to Node.js projects. This reference lists the most frequently used APIs with accurate signatures and runnable snippets.

Core APIs

  • Model.query — Starts a query builder for the model table, optionally bound to a specific connection or transaction.
  • Model.relatedQuery — Returns a query builder scoped to a defined relation for nested reads and writes.
  • withGraphFetched — Eager loads one or more relations in a single query graph to avoid the N+1 problem.

Example

const { Model } = require('objection');

class User extends Model {
  static get tableName() { return 'users'; }
}

const users = await User.query().where('active', true).limit(10);

Notes

Relation expressions are separate from table joins, so define relations in the model class. Eager loading is the main tool against the N+1 problem.

Verification

Fetch a list with withGraphFetched and confirm the generated SQL issues one relation query rather than one per row.

Errors

The following points are quoted verbatim from the official documentation. 来源:https://vincit.github.io/objection.js/ · 取证方式:HTTP GET 官方 README/文档页(HTML 去标签) · 抓取时间:2026-11-07T13:51:16.562Z. Any error type, throw condition or recovery step not stated there is left unspecified; this page does not infer exception classes or return values.

FAQ

Which query builder does Objection use?
Objection delegates SQL generation to Knex, so any Knex query method is available on Model.query().
How do I bind a model to a database connection?
Call Model.knex(knex) once at startup, or pass a knex instance or transaction to Model.query().
How does Objection avoid N+1 queries?
Use withGraphFetched or withGraphJoined to fetch relations in the same query graph instead of querying per row.