DEV Community

Cover image for ObjectionJs & Advanced Techniques
Muhammed Sarbast
Muhammed Sarbast

Posted on

ObjectionJs & Advanced Techniques

Objection.js is a highly flexible and performant Object-Relational Mapping (ORM) library for Node.js, designed to help you build efficient SQL queries with a delightful API. In this blog post, we'll delve into some advanced features that can take your Objection.js skill set to the next level.

1. Eager Loading

One of the greatest features in Objection.js is the ability to use eager loading, reducing the number of queries and thus the overall load on the database. Leveraging the .eager() method, you can load related data in a single query. But have you tried the modifyEager function? This allows you to apply transformations or additional conditions on your eagerly loaded data.

Person.query()
  .eager('pets')
  .modifyEager('pets', builder => builder.where('species', 'dog'))
  .then(persons => {
    // Each person in persons has a 'pets' property that contains only their dogs.
  });
Enter fullscreen mode Exit fullscreen mode

2. Efficient Use of Transactions

Transactions in Objection.js are designed to help you manage your database operations efficiently, ensuring that related operations either all succeed or fail together, maintaining the integrity of your data. The .transaction() method makes it a breeze to use transactions, but you can enhance efficiency by reusing transaction instances for multiple queries.

const trx = await Person.startTransaction();

try {
  await Person.query(trx).insert({name: 'John'});
  await Pet.query(trx).insert({name: 'Fluffy', ownerId: 1});
  await trx.commit();
} catch (err) {
  await trx.rollback();
  throw err;
}
Enter fullscreen mode Exit fullscreen mode

3. Graph Insertion and Upserts

Graph insertion is another Objection.js feature that can help reduce the amount of code you write and the number of database round-trips. It allows you to insert a graph of objects with relations in a single command.

await Person.query().insertGraph({
  name: 'Jennifer',
  pets: [{
    name: 'Fluffy',
    species: 'dog'
  }]
});
Enter fullscreen mode Exit fullscreen mode

What's even more exciting is the combination of graph operations with upserts (update or insert). This is achieved using the upsertGraph method.

await Person.query().upsertGraph({
  id: 1,
  name: 'Jennifer',
  pets: [{
    id: 1,
    name: 'Fluffy',
    species: 'dog'
  }]
}, { relate: true, unrelate: true });
Enter fullscreen mode Exit fullscreen mode

4. Query Context

With the .context() method, you can add a context to your queries, which can be accessed in all query lifecycle methods. This can be highly useful for passing request-specific data, such as the currently logged in user's ID.

Person.query()
  .context({userId: 1})
  .findById(1)
  .then(person => {
    // The context is accessible in person.$beforeInsert, person.$beforeUpdate etc.
  });
Enter fullscreen mode Exit fullscreen mode

Objection.js is a powerful ORM with a host of features that can help developers write efficient, maintainable, and performant SQL-based applications in Node.js. Mastering its advanced features allows for even more refined control and optimization, which will truly help you stand out as a Node.js developer.

Top comments (0)