简体   繁体   English

有没有办法让 TypeORM 返回列 id 作为字符串而不是数字?

[英]Is there a way to make TypeORM return column id as string instead of number?

This is my id column:这是我的 id 列:

@PrimaryGeneratedColumn()
id: number;

Is there a way to return this column as string?有没有办法将此列作为字符串返回? I don't want to change the type in database (it needs to be number because it needs to increment, right?), I just want to return it as string.我不想更改数据库中的类型(它需要是数字,因为它需要增加,对吗?),我只想将它作为字符串返回。

I can do this:我可以做这个:

@PrimaryGeneratedColumn()
id: string;

but it doesn't change the return type, it makes the values being treated as string but it is still a number.但它不会改变返回类型,它使值被视为字符串,但它仍然是一个数字。

I could also:我还可以:

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

but it is kinda tedious to use this method on every entity and every foreign key.但是在每个实体和每个外键上使用这种方法有点乏味。

SOLUTION: It turns out that typeorm was returning number instead of string because it's column type was integer.解决方案:原来 typeorm 返回的是数字而不是字符串,因为它的列类型是 integer。 When I changed column type to bigint it started to return string instead of number.当我将列类型更改为 bigint 时,它开始返回字符串而不是数字。

You can use a custom transform您可以使用自定义转换

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM