0
0
NestJSframework~5 mins

Entity definition in NestJS

Choose your learning style9 modes available
Introduction

An entity defines how data is stored in a database table. It helps NestJS know what data to save and retrieve.

When you want to create a table in your database to store user information.
When you need to map your app's data to database rows and columns.
When you want to use TypeORM or another ORM with NestJS to manage data easily.
When you want to keep your database structure clear and organized in code.
Syntax
NestJS
import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';

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

  @Column()
  name: string;

  @Column({ nullable: true })
  description?: string;
}

@Entity() marks the class as a database table.

@PrimaryGeneratedColumn() creates an auto-incrementing ID.

Examples
This defines a User table with id, username, and email columns.
NestJS
import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';

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

  @Column()
  username: string;

  @Column()
  email: string;
}
This defines a Product table named 'products' with a UUID id and decimal price.
NestJS
import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';

@Entity('products')
export class Product {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @Column()
  title: string;

  @Column('decimal')
  price: number;
}
Sample Program

This Book entity creates a table with id, title, and an optional author column.

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

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

  @Column()
  title: string;

  @Column({ nullable: true })
  author?: string;
}
OutputSuccess
Important Notes

Entity classes must be decorated with @Entity() to work with TypeORM.

Columns can have options like nullable to allow empty values.

Primary keys are usually auto-generated for easy identification.

Summary

Entities map your code classes to database tables.

Use decorators like @Entity() and @Column() to define structure.

This helps NestJS and TypeORM manage data smoothly.