Skip to content

Documents ​

Objection.js makes it easy to store non-flat documents as table rows. All properties of a model that are marked as objects or arrays in the model's jsonSchema are automatically converted to JSON strings in the database and back to objects when read from the database. The database columns for the object properties can be normal text columns. Postgresql has the json and jsonb data types and MySQL has the json data type, which can be used instead for better performance and possibility to query the documents. Field expressions like ref('address:city') and the whereJson* methods work on postgres and MySQL, and throw on other databases. See MySQL. If you don't want to use jsonSchema you can mark properties as objects using the jsonAttributes Model property.

The address property of the Person model is defined as an object in the Person.jsonSchema:

js
const jennifer = await Person.query().insert({
  firstName: 'Jennifer',
  lastName: 'Lawrence',
  age: 24,
  address: {
    street: 'Somestreet 10',
    zipCode: '123456',
    city: 'Tampere'
  }
});

const jenniferFromDb = await Person.query().findById(jennifer.id);

console.log(jennifer.address.city); // --> Tampere
console.log(jenniferFromDb.address.city); // --> Tampere

MIT Licensed. Built on objection.js by Sami Koskimäki and its contributors.