【问题标题】:Is there a way to make TypeORM return column id as string instead of number?有没有办法让 TypeORM 返回列 id 作为字符串而不是数字?
【发布时间】:2021-06-20 05:58:33
【问题描述】:

这是我的 id 列:

@PrimaryGeneratedColumn()
id: number;

有没有办法将此列作为字符串返回?我不想更改数据库中的类型(它需要是数字,因为它需要递增,对吗?),我只想将它作为字符串返回。

我可以这样做:

@PrimaryGeneratedColumn()
id: string;

但它不会改变返回类型,它使值被视为字符串但它仍然是一个数字。

我也可以:

  @AfterLoad()
  idToString(): void {
    this.id = this.id.toString();
  }

但是在每个实体和每个外键上都使用这种方法有点乏味。

解决方案: 事实证明 typeorm 返回的是数字而不是字符串,因为它的列类型是整数。当我将列类型更改为 bigint 时,它开始返回字符串而不是数字。

【问题讨论】:

  • 感谢您的提示!

标签: node.js postgresql typeorm


【解决方案1】:

您可以使用自定义转换

import { Transform } from 'class-transformer';
@PrimaryGeneratedColumn()
@Transform(({ value }) => (value).toString())
id: number;

【讨论】:

    猜你喜欢
    • 2019-10-22
    • 2022-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    • 2020-11-20
    相关资源
    最近更新 更多