Objection.js: Boolean fields are read as 1/0 instead of true/false

Created on 2 Aug 2016  路  3Comments  路  Source: Vincit/objection.js

Not sure if this is SQLite3 specific but it looks like it's not converting 0 & 1 to true & false after .query().select()....
It's probably a Knex thing.. if you got info or any comments...

Most helpful comment

Since Objection doesn't handle this, one solution is to use knex's typeCast option. (The only mention I could find is this StackOverflow answer.)

const knex = require('knex')({
  client: 'mysql2',
  connection: {
    host: 'localhost',
    user: 'mysql',
    password: 'mysql',
    database: 'mysql',
    typeCast (field, next) {
      // Convert 1 to true, 0 to false, and leave null alone
      if (field.type === 'TINY' && field.length === 1) {
        const value = field.string()
        return value ? value === '1' : null
      }
      return next()
    }
  }
})

All 3 comments

Yeah as far as I know it is knex / underlying driver thing. I had problems with that when I wrote migration table locking feature to knex.

Objection doesn't touch the values coming from the db driver by default. As elhigu mentioned, this is a knex/db client issue.

Since Objection doesn't handle this, one solution is to use knex's typeCast option. (The only mention I could find is this StackOverflow answer.)

const knex = require('knex')({
  client: 'mysql2',
  connection: {
    host: 'localhost',
    user: 'mysql',
    password: 'mysql',
    database: 'mysql',
    typeCast (field, next) {
      // Convert 1 to true, 0 to false, and leave null alone
      if (field.type === 'TINY' && field.length === 1) {
        const value = field.string()
        return value ? value === '1' : null
      }
      return next()
    }
  }
})

Was this page helpful?
0 / 5 - 0 ratings