TypeORM: Adding Fields with Nullable/Default Data

Updated: February 25, 2022 By: A Goodman 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

Related Articles