How to set the default value in TypeORM?

by santina.kub , in category: JavaScript , a year ago

How to set the default value in TypeORM?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by carlo , a year ago

@santina.kub 

To set the default value for a column in TypeORM, you can use the default property of the column decorator. For example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';

@Entity()
export class User {
  @PrimaryGeneratedColumn()
  id: number;

  @Column({ default: 'John' })
  name: string;

  @Column({ default: false })
  isAdmin: boolean;
}


In this example, the name column will have a default value of 'John' and the isAdmin column will have a default value of false. When you insert a new row into the User table, these columns will automatically be given their default values if you don't specify a value for them.


Note that the default value will only be used when inserting a new row into the database. If you update an existing row and don't specify a new value for one of these columns, the default value will not be used.


You can also use the @UpdateDateColumn and @CreateDateColumn decorators to automatically set the current date and time as the default value for a column when inserting or updating a row.

Member

by uriah , 4 months ago

@santina.kub 

Here's an example of how to use the @CreateDateColumn decorator to set the default value of a column to the current date and time:


1 2 3 4 5 6 7


import { Entity, Column, PrimaryGeneratedColumn, CreateDateColumn } from 'typeorm';


@Entity() export class User { @PrimaryGeneratedColumn() id: number;


@Column() name: string;


@CreateDateColumn({ default: () => 'CURRENT_TIMESTAMP' }) createdAt: Date; }


In this example, the createdAt column will have a default value of the current date and time when a new row is inserted. The () => 'CURRENT_TIMESTAMP' syntax is used to tell TypeORM to use the SQL function CURRENT_TIMESTAMP as the default value.You can also use other SQL functions, such as NOW() or any other date and time function supported by your database. For example, if you're using PostgreSQL, you can use the now() function like this:


1 2 3 4 5


import { Entity, Column, PrimaryGeneratedColumn, CreateDateColumn } from 'typeorm';


@Entity() export class User { @PrimaryGeneratedColumn() id: number;


@Column() name: string;


@CreateDateColumn({ default: () => 'now()' }) createdAt: Date; }


With this configuration, the createdAt column will have a default value of the current date and time provided by the now() function in PostgreSQL.