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 }
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 }
}
}
}
Most helpful comment
Excellent, thanks! For anyone else who stumbles upon this issue, you would also need to add
nullas an allowable type to your optional properties, like so...