【问题标题】:TypeORM jsonb array columnTypeORM jsonb 数组列
【发布时间】:2020-04-13 16:24:57
【问题描述】:

我在做一个node微服务,orm和db分别是typeormpostgresql

我正在尝试创建 jsonb 数组列,但我可能没有以正确的方式进行操作。

备注

  1. 我通常只需添加一个简单的额外实体和关系即可完成此操作。在这种情况下,我被要求在 oder 中使用 jsonb 类型,以便能够在不适应架构更改的情况下修改界面。
  2. 现在存储一个简单的索引 id 列表就足够了。
  3. 我不确定是否应该使用array: true 列选项。我尝试使用普通的 jsonb 对象但没有成功("{}"::jsonb)。

我的目标:

存储具有索引 id 列的对象数组,并能够添加和删除ID。万一这是不可能的,一个平面索引字符串数组就可以了。

例如:

[ {id: 'some-uuid-000'}, {id: 'some-uuid-001'}, ... ]

或:

['some-uuid-000', 'some-uuid-001', 'some-uuid-002']

代码:

我的栏目定义:

@Column({
        type: 'jsonb',
        array: true,
        default: () => 'ARRAY[]::jsonb[]',
        nullable: false,
    })
    public users: Array<{ id: string }> = [];

我设法用

获取空数组
const group = await repo.findOneOrFail({ id: groupId });
console.log('>>>>>', group.users);

哪个输出:

>>>>> []

当尝试向数组中添加一个项目并保持如下时

return repo.update(groupId, { users: [...group.users, { id: userId }] });

我得到以下输出:

2019-12-21 14:40:44.088 UTC [556] ERROR:  malformed array literal: "[{"id":"cc135b8a-b6ed-4cd7-99fc-396228e74509"}]"
2019-12-21 14:40:44.088 UTC [556] DETAIL:  "[" must introduce explicitly-specified array dimensions.
2019-12-21 14:40:44.088 UTC [556] STATEMENT:  UPDATE "group" SET "users" = $2, "created_at" = CURRENT_TIMESTAMP WHERE "id" IN ($1)
(node:5050) UnhandledPromiseRejectionWarning: QueryFailedError: malformed array literal: "[{"id":"cc135b8a-b6ed-4cd7-99fc-396228e74509"}]"

输出错误告诉我配置一定是错误的,因为 postgres 似乎提供了一个普通的对象数组,而期望不同的格式/表示法。我没有在文档中找到有关此类场景的详细信息。

【问题讨论】:

    标签: node.js postgresql typescript orm typeorm


    【解决方案1】:

    最终我找到了以下解决方案:罪魁祸首是 array 列选项,需要显式设置为 false,如下例所示:

    @Column({
            type: 'jsonb',
            array: false,
            default: () => "'[]'",
            nullable: false,
        })
        public users!: Array<{ id: string }>;
    

    如果未设置 typeorm 会自动推断 postgres 列类型为 jsonb[](而不是普通的 jsonb),这不允许执行 jsonb_set 操作。

    【讨论】:

    • 仍然会报错,error: malformed array literal: "[]"
    猜你喜欢
    • 2021-01-29
    • 1970-01-01
    • 2021-02-22
    • 2023-03-16
    • 2021-12-12
    • 1970-01-01
    • 1970-01-01
    • 2016-11-25
    • 2021-05-07
    相关资源
    最近更新 更多