When I query with Knex.js a Postgres database boolean fields it returns the result as "0"
or "1"
(as strings) instead of the boolean values true
and false
.
Is there a way to make Knex/Postgres return boolean fields automatically as boolean values?
EDIT: I’m using Knex
with node-postgres
,
here are my table definitions:
JavaScript
x
18
18
1
knex.schema
2
.createTable('users_table', (table) => {
3
table.increments('id');
4
table.string('email').unique().notNullable();
5
table.string('full_name').notNullable();
6
table.timestamp('created_at').defaultTo(knex.fn.now()).notNullable();
7
8
table.index('email', 'email_unique', 'unique');
9
})
10
.createTable('users_credentials', (table) => {
11
table.increments('id');
12
table.string('password').notNullable();
13
table.boolean('is_activated').defaultTo(false).notNullable();
14
table.integer('user_id').unsigned().references('users_table.id').notNullable();
15
16
table.index('user_id', 'user_id_unique', 'unique');
17
});
18
Advertisement
Answer
I needed to use the pg.types module:
JavaScript
1
6
1
import { types } from "pg";
2
3
types.setTypeParser(16, (value) => { // 16 is the type enum vaue of boolean
4
return Boolean(parseInt(value));
5
});
6