简体   繁体   中英

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

This is my id column:

@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. When I changed column type to bigint it started to return string instead of number.

You can use a custom transform

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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