0
# Objection.js
1
2
Objection.js is an SQL-friendly ORM for Node.js built on top of Knex.js. It provides powerful query building capabilities, robust relationship handling, JSON schema validation, and graph operations while maintaining full SQL power and flexibility.
3
4
## Package Information
5
6
- **Package Name**: objection
7
- **Package Type**: npm
8
- **Language**: JavaScript/TypeScript
9
- **Installation**: `npm install objection knex`
10
- **Database Support**: PostgreSQL, MySQL, SQLite3
11
- **Requirements**: Node.js >=14.0.0, Knex.js >=1.0.1
12
13
## Core Imports
14
15
```javascript
16
const { Model, QueryBuilder, transaction, raw, ref, fn } = require('objection');
17
```
18
19
For ES modules:
20
21
```javascript
22
import { Model, QueryBuilder, transaction, raw, ref, fn } from 'objection';
23
```
24
25
TypeScript:
26
27
```typescript
28
import { Model, QueryBuilder, transaction, raw, ref, fn } from 'objection';
29
```
30
31
## Basic Usage
32
33
```javascript
34
const { Model } = require('objection');
35
const Knex = require('knex');
36
37
// Initialize knex
38
const knex = Knex({
39
client: 'sqlite3',
40
connection: { filename: './database.sqlite' }
41
});
42
43
// Bind knex to Model
44
Model.knex(knex);
45
46
// Define a model
47
class Person extends Model {
48
static get tableName() {
49
return 'persons';
50
}
51
52
static get relationMappings() {
53
return {
54
pets: {
55
relation: Model.HasManyRelation,
56
modelClass: Pet,
57
join: {
58
from: 'persons.id',
59
to: 'pets.ownerId'
60
}
61
}
62
};
63
}
64
}
65
66
// Use the model
67
const person = await Person.query()
68
.insert({ firstName: 'John', lastName: 'Doe' });
69
70
const people = await Person.query()
71
.withGraphFetched('pets')
72
.where('age', '>', 18);
73
```
74
75
## Architecture
76
77
Objection.js is built around several key components:
78
79
- **Model System**: Base `Model` class for defining database entities with validation and relationships
80
- **Query Builder**: Powerful chainable query interface built on Knex.js with additional ORM features
81
- **Relation System**: Five relation types for modeling database relationships with eager loading support
82
- **Graph Operations**: Insert, update, and upsert operations for complex nested data structures
83
- **Transaction Support**: Database transactions with model binding and rollback capabilities
84
- **Validation Engine**: JSON Schema validation with custom validator support
85
86
## Capabilities
87
88
### Model Definition and Querying
89
90
Core model functionality for defining database entities, validation, and basic CRUD operations.
91
92
```javascript { .api }
93
class Model {
94
static get tableName(): string;
95
static get idColumn(): string | string[];
96
static get jsonSchema(): object;
97
static get relationMappings(): object;
98
99
static query(trx?: Transaction): QueryBuilder;
100
static fromJson(json: object, options?: ModelOptions): Model;
101
102
$query(trx?: Transaction): QueryBuilder;
103
$id(id?: any): any;
104
$toJson(options?: ToJsonOptions): object;
105
}
106
```
107
108
[Model Definition and Querying](./model-definition.md)
109
110
### Query Building
111
112
Advanced query building with chainable methods, joins, aggregates, and complex WHERE conditions.
113
114
```javascript { .api }
115
class QueryBuilder {
116
select(...columns: string[]): QueryBuilder;
117
where(column: string, operator: string, value: any): QueryBuilder;
118
join(table: string, leftCol: string, rightCol: string): QueryBuilder;
119
orderBy(column: string, direction?: 'asc' | 'desc'): QueryBuilder;
120
121
insert(data: object | object[]): QueryBuilder;
122
update(data: object): QueryBuilder;
123
delete(): QueryBuilder;
124
125
withGraphFetched(expression: string): QueryBuilder;
126
}
127
```
128
129
[Query Building](./query-building.md)
130
131
### Relationships and Eager Loading
132
133
Relationship definitions and eager loading patterns for efficient data fetching.
134
135
```javascript { .api }
136
// Relation types
137
const HasOneRelation: RelationType;
138
const HasManyRelation: RelationType;
139
const BelongsToOneRelation: RelationType;
140
const ManyToManyRelation: RelationType;
141
const HasOneThroughRelation: RelationType;
142
143
interface RelationMapping {
144
relation: RelationType;
145
modelClass: typeof Model;
146
join: {
147
from: string;
148
to: string;
149
through?: object;
150
};
151
}
152
```
153
154
[Relationships and Eager Loading](./relationships.md)
155
156
### Graph Operations
157
158
Insert, update, and upsert operations for complex nested data structures with relationship handling.
159
160
```javascript { .api }
161
insertGraph(graph: object | object[], options?: InsertGraphOptions): QueryBuilder;
162
upsertGraph(graph: object | object[], options?: UpsertGraphOptions): QueryBuilder;
163
164
interface InsertGraphOptions {
165
relate?: boolean | string[];
166
allowRefs?: boolean;
167
}
168
169
interface UpsertGraphOptions {
170
relate?: boolean | string[];
171
unrelate?: boolean | string[];
172
insertMissing?: boolean | string[];
173
update?: boolean | string[];
174
noInsert?: boolean | string[];
175
noUpdate?: boolean | string[];
176
noDelete?: boolean | string[];
177
}
178
```
179
180
[Graph Operations](./graph-operations.md)
181
182
### Transactions
183
184
Database transaction management with model binding and automatic rollback.
185
186
```javascript { .api }
187
function transaction<T>(
188
callback: (trx: Transaction) => Promise<T>
189
): Promise<T>;
190
191
function transaction<T>(
192
knex: Knex,
193
callback: (trx: Transaction) => Promise<T>
194
): Promise<T>;
195
```
196
197
[Transactions](./transactions.md)
198
199
### Expression Builders
200
201
Query expression builders for raw SQL, column references, values, and functions.
202
203
```javascript { .api }
204
function raw(sql: string, ...bindings: any[]): RawBuilder;
205
function ref(expression: string): ReferenceBuilder;
206
function val(value: any): ValueBuilder;
207
function fn(functionName: string, ...args: any[]): FunctionBuilder;
208
```
209
210
[Expression Builders](./expression-builders.md)
211
212
### Validation and Error Handling
213
214
JSON Schema validation system and comprehensive error types for database constraints.
215
216
```javascript { .api }
217
class ValidationError extends Error {
218
statusCode: number;
219
data: object;
220
type: string;
221
}
222
223
class NotFoundError extends Error {
224
statusCode: number;
225
type: 'NotFound';
226
}
227
228
class AjvValidator {
229
constructor(config: AjvConfig);
230
validate(args: ValidatorArgs): object;
231
}
232
```
233
234
[Validation and Error Handling](./validation.md)
235
236
### Utilities and Plugins
237
238
Utility functions for column mapping, mixins, and extending model functionality.
239
240
```javascript { .api }
241
function snakeCaseMappers(options?: SnakeCaseMappersOptions): ColumnNameMappers;
242
function knexSnakeCaseMappers(options?: SnakeCaseMappersOptions): KnexMappers;
243
function mixin(modelClass: typeof Model, ...plugins: Plugin[]): typeof Model;
244
function compose(...plugins: Plugin[]): Plugin;
245
```
246
247
[Utilities and Plugins](./utilities.md)
248
249
## Types
250
251
```typescript { .api }
252
type Transaction = Knex.Transaction;
253
type RelationExpression = string | object;
254
type MaybeCompositeId = string | number | Array<string | number>;
255
256
interface ModelOptions {
257
patch?: boolean;
258
skipValidation?: boolean;
259
}
260
261
interface ToJsonOptions {
262
virtuals?: boolean | string[];
263
shallow?: boolean;
264
}
265
266
interface QueryContext {
267
transaction?: Transaction;
268
[key: string]: any;
269
}
270
```