【问题标题】:Knex.js with Postgres returns boolean fields as "0" or "1" instead of booleans带有 Postgres 的 Knex.js 将布尔字段返回为“0”或“1”而不是布尔值
【发布时间】:2021-09-20 12:55:12
【问题描述】:

当我使用 Knex.js 查询 Postgres 数据库布尔字段时,它以 "0""1"(作为字符串)返回结果,而不是布尔值 truefalse

有没有办法让 Knex/Postgres 自动将布尔字段作为布尔值返回?

编辑:我正在使用Knexnode-postgres, 这是我的表定义:

knex.schema
  .createTable('users_table', (table) => {
    table.increments('id');
    table.string('email').unique().notNullable();
    table.string('full_name').notNullable();
    table.timestamp('created_at').defaultTo(knex.fn.now()).notNullable();

    table.index('email', 'email_unique', 'unique');
  })
  .createTable('users_credentials', (table) => {
    table.increments('id');
    table.string('password').notNullable();
    table.boolean('is_activated').defaultTo(false).notNullable();
    table.integer('user_id').unsigned().references('users_table.id').notNullable();

    table.index('user_id', 'user_id_unique', 'unique');
  });

【问题讨论】:

  • 这个问题需要更多信息:1) 正在使用的 Postgres 驱动程序 2) Postgres 和 Knex 中的表定义。添加为问题的更新。
  • @AdrianKlaver 我已经更新了问题
  • 看起来你需要深入研究这个pg-types 并可能覆盖解析器。尽管在查询中预感将布尔值转换为文本,例如bool_val::text 看看会发生什么。

标签: javascript postgresql knex.js


【解决方案1】:

我需要使用 pg.types 模块:

import { types } from "pg";

types.setTypeParser(16, (value) => { // 16 is the type enum vaue of boolean
    return Boolean(parseInt(value));
});

【讨论】:

  • 这很奇怪。 knex 不是开箱即用地依赖 pgpg-types 吗?
  • @Bergi 是的,它确实如此,Cubear Guy 正在做的是根据此处的说明覆盖内置解析器 node-og-types
  • @AdrianKlaver 我的观点是 node-pg-types 带有一个 builtin boolean parser ,它不需要被覆盖。之前一定有什么东西禁用了它。
猜你喜欢
  • 1970-01-01
  • 2015-02-19
  • 2017-11-13
  • 2021-09-11
  • 2020-03-15
  • 1970-01-01
  • 1970-01-01
  • 2017-04-22
  • 2020-02-13
相关资源
最近更新 更多