Skip to content
Tutorials Center
My learning

Topics

Lesson 5 of 37 ยท Models and Entities

TypeORM Entities and Columns

Define TypeORM entities with @Entity and @Column, set column names and options, share fields with abstract base classes and embedded objects, and see metadata in a runnable stand-in.

In TypeORM an entity is a class with decorators. The decorators do not run SQL; they record metadata (table name, column names, types) that the DataSource later reads to build queries and DDL. Understanding that makes the whole API feel less magical.

Library code is read-only. The stand-ins mimic the metadata step with plain functions, because Node's runner does not compile decorators.

@Entity and @Column

TypeScript
import { Entity, PrimaryGeneratedColumn, Column } from "typeorm";

@Entity({ name: "products" })
export class Product {
  @PrimaryGeneratedColumn()
  id!: number;

  @Column({ type: "varchar", length: 120 })
  title!: string;

  @Column({ name: "price_cents", type: "int" })
  priceCents!: number;

  @Column({ type: "text", nullable: true })
  description!: string | null;

  @Column({ default: true })
  inStock!: boolean;
}

Options you will use most on @Column:

Option Meaning
type Database column type ("varchar", "int", "text", "timestamp", ...)
name Column name in the table (defaults to the property name)
length Size for varchar
nullable Allow NULL (default false)
default Default value or SQL expression
unique Add a unique constraint
select false hides the column from default queries (good for password hashes)
transformer Convert between database and JavaScript values

Prefer an explicit type for anything beyond simple strings and numbers; the inferred type is a guess from TypeScript metadata (a string | null property, for example, would be read as Object).

Special columns

TypeScript
import { CreateDateColumn, UpdateDateColumn, DeleteDateColumn, VersionColumn } from "typeorm";

@Entity()
export class Article {
  @PrimaryGeneratedColumn("uuid") id!: string;
  @CreateDateColumn() createdAt!: Date;     // set once on insert
  @UpdateDateColumn() updatedAt!: Date;     // refreshed on every save
  @DeleteDateColumn() deletedAt?: Date;     // soft delete marker
  @VersionColumn() version!: number;        // optimistic locking counter
}

Lesson 5 of this chapter covers timestamps and soft deletes in depth.

Share fields: base classes and embedded objects

Repeated columns belong in an abstract base class. Entities that extend it get its columns, but the base itself has no table.

TypeScript
export abstract class Timestamps {
  @CreateDateColumn() createdAt!: Date;
  @UpdateDateColumn() updatedAt!: Date;
}

@Entity()
export class Customer extends Timestamps {
  @PrimaryGeneratedColumn() id!: number;
  @Column() email!: string;
}

An embedded class groups columns that belong together into one object property:

TypeScript
export class Address {
  @Column() street!: string;
  @Column() city!: string;
}

@Entity()
export class Shop {
  @PrimaryGeneratedColumn() id!: number;
  @Column(() => Address) address!: Address;   // columns: addressStreet, addressCity
}

Embedded columns are stored in the same table, prefixed with the property name.

A snake_case naming strategy

Many teams want createdAt in code but created_at in the database. Instead of writing name: on every column, TypeORM lets you supply a naming strategy class (extend DefaultNamingStrategy and override columnName). Packages such as typeorm-naming-strategies provide ready-made ones. The conversion itself is plain string work:

Node.js camelCase to snake_case

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Metadata, the stand-in way

A decorator such as @Column() appends to a registry. This stand-in does the same with function calls and then builds the SQL and hydrates rows from that registry.

Node.js Entity metadata registry

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Real TypeORM does exactly this, plus much more: relations, indexes, inheritance and caching of the metadata.

Common mistakes

  • Forgetting nullable: true on a column whose property type is string | null, then wondering why inserts fail.
  • Leaving the type to inference for unions, which produces Object and an error at start-up.
  • Declaring entities but not listing them in the DataSource entities option (or the glob misses compiled .js files in dist/).
  • Putting business logic in entity constructors; TypeORM creates instances without calling your constructor arguments.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What do TypeORM decorators like @Column actually do?

    Decorators store metadata about the class; queries and DDL are built from it.
  2. 2. How do you give a property a different column name in the table?

    The name option sets the column name; a naming strategy can do it globally.
  3. 3. What is an abstract base class used for in TypeORM?

    Entities extending it inherit its columns; the base class itself is not a table.
  4. 4. What does select: false on a column do?

    It keeps values such as password hashes out of normal results unless you ask for them.

Summary

  • @Entity maps a class to a table; @Column maps a property to a column.
  • Use explicit type, nullable, name and default rather than relying on inference.
  • @CreateDateColumn, @UpdateDateColumn, @DeleteDateColumn and @VersionColumn handle common bookkeeping.
  • Abstract base classes and embedded classes remove repeated columns.
  • Decorators build metadata; the DataSource turns it into SQL.

Next: Sequelize Models and init()