1

I'm building an API using AdonisJS with PostgreSQL.

Some of my entities have optional fields. For example: a user may or may not have a phone number.

I'm having trouble deciding the best and most acceptable way to clear an optional field value (e.g. setting the phone field to null in the database) using TypeScript.

I believe the proper way would be to mark the field as optional in the class and set it to undefined, but that has no effect. I can (and am, for the moment) marking the field as being nullable, but I don't think that's the best practice.

This is the migration file (simplified):

export default class Users extends BaseSchema {
  protected tableName = 'users'

  public async up() {
    this.schema.createTable(this.tableName, (table) => {
      table.string('phone', 11).unique()
    })
  }
}

If I mark the phone field as optional in the model class (simplified):

export default class User extends BaseModel {
  @column()
  public phone?: string
}

and try to set the field as undefined before saving, nothing happens:

const user = new User()
user.phone = '12345678910'
await user.save()

user.phone = undefined
await user.save()
// user phone is still '12345678910' in the database

So, I'm doing this:

export default class User extends BaseModel {
  @column()
  public phone: string | null
}

const user = new User()
user.phone = '12345678910'
await user.save()

user.phone = null
await user.save()
// user phone is now null in the database, as intended

The AdonisJS / Lucid docs do not tell the best way (according to the framework) to set optional fields as null in the database. Anyone knows how?

Ernani
  • 319
  • 1
  • 4
  • 18
  • 2
    It's not specifically mentioned in the docs regarding nullable fields, but the optional field named ```avatarUrl``` is treated the same way here https://docs.adonisjs.com/guides/models/introduction#defining-columns as you have mentioned. – Asad Jivani Aug 09 '21 at 20:26

0 Answers0