TypeORM: Adding Fields with Nullable/Default Data

Last updated on February 25, 2022 A Goodman Loading... Post a comment

By default, every field (column) of a TypeORM entity is NOT NULL. You can make a specific field become nullable by setting the nullable option to true, like this:

// book.entity.ts
import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
} from 'typeorm'

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

  @Column()
  title: string;

  // This column is nullable
  @Column({ nullable: true })
  auther: string;
}

In case you want to add the column’s DEFAULT value:

// book.entity.ts
import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
} from 'typeorm'

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

  @Column()
  title: string;

  // This column is nullable
  @Column({ nullable: true })
  auther: string;

  // The default price = 0 means a book is free
  @Column({default: 0})
  price: number;
}

You can learn more about TypeORM in the official docs (typeorm.io).

Further reading:

You can also check out our database topic page for the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

You May Also Like