Objection.js: Model properties: null vs undefined

Created on 9 Nov 2019  路  2Comments  路  Source: Vincit/objection.js

Let's say I have the following Person model, where only name is required. age and address are optional.

class Person extends Base {

  static get tableName() {
    return 'person'
  }

  static get jsonSchema () {
    return {
      type: 'object',
      required: [ 'name' ],
      properties: {
        name: { type: 'string' },
        age: { type: 'integer' },
        address: { type: 'string' }
      }
    }
  }

}

Now, let's instantiate a Person with only a name. The optional age and address properties are omitted.

const bob = Person.fromJson({ name: 'Bob' })

If we inspect our new friend bob, we see that age and address do not exist, i.e. they are undefined.

console.log(bob)  // =>  { name: 'Bob' }

So here is my question... __does Objection.js provide a built-in way to instantiate new model instances to where missing but optional properties (as defined in the jsonSchema) exist on the new model and are set to null, rather than undefined?__

For example, I'm wanting a simple way to achieve this...

const bob = Person.fromJson({ name: 'Bob' })
console.log(bob)  // =>  { name: 'Bob', age: null, address: null }

Most helpful comment

Excellent, thanks! For anyone else who stumbles upon this issue, you would also need to add null as an allowable type to your optional properties, like so...

  static get jsonSchema () {
    return {
      type: 'object',
      required: [ 'name' ],
      properties: {
        name: { type: 'string' },
        age: { type: ['integer', 'null'], default: null },
        address: { type: ['string', 'null'], default: null }
      }
    }
  }

All 2 comments

You can use default: null in jsonSchema

Excellent, thanks! For anyone else who stumbles upon this issue, you would also need to add null as an allowable type to your optional properties, like so...

  static get jsonSchema () {
    return {
      type: 'object',
      required: [ 'name' ],
      properties: {
        name: { type: 'string' },
        age: { type: ['integer', 'null'], default: null },
        address: { type: ['string', 'null'], default: null }
      }
    }
  }
Was this page helpful?
0 / 5 - 0 ratings

Related issues

zuck picture zuck  路  4Comments

zacharynevin picture zacharynevin  路  4Comments

haywirez picture haywirez  路  3Comments

rickmed picture rickmed  路  4Comments

nicolaracco picture nicolaracco  路  3Comments