Ashish Choubey
Ashish Choubey

Reputation: 457

How to store big int in nest js using typeorm

some.entity.ts

amount:number

But when I store a very large data in my postgres it throws error '''integer out of range'''

My question is how can I store Big Int as type in psql using typeorm

Upvotes: 16

Views: 28097

Answers (5)

Eddie R
Eddie R

Reputation: 574

For PostgreSQL connection type you can specify parseInt8: true option in your Datasource definition (along with options like type, host, port and so on).

Then change the type of column to bigint in entity file:

@Column({type: 'bigint'})
columnName: bigint

Now after retrieving data from the table with columnName you'll get columnName as bigint, not a string.

P.S. Option bigNumberStrings works just for MySQL/MariaDB.

Upvotes: 1

zemil
zemil

Reputation: 5084

I used column transformer:

export class ColumnNumberTransformer {
    public to(data: number): number {
        return data;
    }

    public from(data: string): number {
        // output value, you can use Number, parseFloat variations
        // also you can add nullable condition:
        // if (!Boolean(data)) return 0;

        return parseInt(data);
    }
}

Then in entity:

@Entity('accounts')
export class AccountEntity extends BaseEntity {
    @Column({
        type: 'bigint',
        nullable: false,
        transformer: new ColumnNumberTransformer()
    })
    public balance: number;
}

Upvotes: 1

Evil Cheetah
Evil Cheetah

Reputation: 113

Great resonse from @Riajul Islam!

As an addition to his answer, if you want to store bigint in PrimaryGeneratedColumn, you should you the following:

    @PrimaryGeneratedColumn( 'increment', {type: 'bigint'} )
    id: number;

Upvotes: 7

Riajul Islam
Riajul Islam

Reputation: 1483

Define type bigint in @Column decorator,

@Column({type: 'bigint'})
columnName: string;

Note: that based on TypeOrm documentation bigint is mapped to string.

Upvotes: 24

Lanistor
Lanistor

Reputation: 303

Just add { bigNumberStrings: false } to TypeORM's configuration, such as:

TypeOrmModule.forRoot({
  bigNumberStrings: false,
  ...config.database,
}),

Then the bigint will return number type.

Upvotes: 7

Related Questions