Dav*_*ide 3 postgresql orm node.js typescript typeorm
我在做一个节点微服务,orm 和 db 分别是typeorm和postgresql
我正在尝试创建jsonb数组列,但我可能没有以正确的方式进行。
笔记
jsonboder 中的类型,以便能够在不满足架构更改的情况下修改接口。array: truecolumn 选项。我尝试了几次使用普通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 }> = [];
Run Code Online (Sandbox Code Playgroud)
我设法获取空数组
const group = await repo.findOneOrFail({ id: groupId });
console.log('>>>>>', group.users);
Run Code Online (Sandbox Code Playgroud)
输出:
>>>>> []
Run Code Online (Sandbox Code Playgroud)
尝试将项目添加到数组并保持如下时
return repo.update(groupId, { users: [...group.users, { id: userId }] });
Run Code Online (Sandbox Code Playgroud)
我得到以下输出:
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"}]"
Run Code Online (Sandbox Code Playgroud)
输出错误告诉我配置一定是错误的,因为 postgres 似乎提供了一个普通的对象数组,同时期待不同的格式/符号。我在文档中没有找到关于这种场景的太多细节。
Dav*_*ide 17
最终我找到了以下解决方案:罪魁祸首是array需要显式设置为 false的列选项,如下例所示:
@Column({
type: 'jsonb',
array: false,
default: () => "'[]'",
nullable: false,
})
public users!: Array<{ id: string }>;
Run Code Online (Sandbox Code Playgroud)
当未设置 typeorm 时,会自动推断 postgres 列类型为jsonb[](而不是 plain jsonb),它不允许执行jsonb_set操作。
| 归档时间: |
|
| 查看次数: |
14047 次 |
| 最近记录: |