Introduction to Objection ORM
Objection.js is a powerful ORM (Object-Relational Mapper) for Node.js, built on top of the SQL query builder Knex. It provides a straightforward solution for interacting with relational databases using JavaScript/TypeScript.
Key Features
- Support for numerous SQL databases through Knex.js.
- Document-based querying with JSON schemas.
- Powerful and customizable querying capabilities.
- Easy-to-use migration and seeding functionality.
Setting Up Objection.js
const { Model } = require('objection');
const Knex = require('knex');
// Initialize knex.
const knex = Knex({
client: 'sqlite3',
connection: {
filename: './mydb.sqlite'
}
});
// Bind all models to the knex instance.
Model.knex(knex);
Example: Defining Models and Queries
Defining a Model
const { Model } = require('objection');
class Person extends Model {
static get tableName() {
return 'persons';
}
static get idColumn() {
return 'id';
}
static get jsonSchema() {
return {
type: 'object',
required: ['firstName', 'lastName'],
properties: {
id: { type: 'integer' },
firstName: { type: 'string', minLength: 1, maxLength: 255 },
lastName: { type: 'string', minLength: 1, maxLength: 255 },
}
};
}
}
Basic Queries
// Insert a new person.
await Person.query().insert({ firstName: 'John', lastName: 'Doe' });
// Fetch a person by ID.
const person = await Person.query().findById(1);
// Fetch all persons.
const persons = await Person.query().select('*');
Advanced Queries
// Fetch persons with certain criteria.
const persons = await Person.query().where('firstName', 'John').orWhere('lastName', 'Smith');
// Update a person.
await Person.query().patchAndFetchById(1, { lastName: 'Doe-Smith' });
// Delete a person.
await Person.query().deleteById(1);
Relationship Mapping
class Animal extends Model {
static get tableName() {
return 'animals';
}
static get relationMappings() {
return {
owner: {
relation: Model.BelongsToOneRelation,
modelClass: Person,
join: {
from: 'animals.ownerId',
to: 'persons.id'
}
}
};
}
}
Fetching Related Data
// Fetch animal with its owner.
const animals = await Animal.query().withGraphFetched('owner');
Building a Simple App with Objection.js
Let’s build a simple Node.js application that connects to an SQLite database using Objection.js.
App Setup
const express = require('express');
const { Model } = require('objection');
const Knex = require('knex');
const app = express();
// Initialize knex.
const knex = Knex({
client: 'sqlite3',
connection: {
filename: './mydb.sqlite'
}
});
// Bind all models to the knex instance.
Model.knex(knex);
// Define models.
class Person extends Model {
static get tableName() {
return 'persons';
}
}
// Route to fetch all persons.
app.get('/persons', async (req, res) => {
const persons = await Person.query();
res.json(persons);
});
// Start the server.
app.listen(3000, () => {
console.log('App listening on port 3000');
});
With this simple setup, you can interact with an SQLite database using Objection.js, performing CRUD operations and more.
Hash: 4194b692f5789e4b223671d25da3dd235692fd43dc7df93536bbc79edd70b8e0