0
0
NestjsHow-ToBeginner ยท 4 min read

How to Create Entity in TypeORM with NestJS: Simple Guide

To create an entity in TypeORM with NestJS, define a class decorated with @Entity() and use decorators like @PrimaryGeneratedColumn() and @Column() to specify table columns. This class represents a database table and its columns in your NestJS app.
๐Ÿ“

Syntax

To create an entity in TypeORM with NestJS, you define a class and decorate it with @Entity(). Inside the class, use @PrimaryGeneratedColumn() for the primary key and @Column() for other fields.

  • @Entity(): Marks the class as a database table.
  • @PrimaryGeneratedColumn(): Creates an auto-incrementing primary key column.
  • @Column(): Defines a regular column in the table.
typescript
import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm';

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

  @Column()
  name: string;

  @Column()
  email: string;
}
๐Ÿ’ป

Example

This example shows a simple User entity with an auto-generated id and two columns: name and email. This entity maps to a user table in the database.

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

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

  @Column({ length: 100 })
  name: string;

  @Column({ unique: true })
  email: string;
}

// Usage in a NestJS service
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';

@Injectable()
export class UserService {
  constructor(
    @InjectRepository(User)
    private userRepository: Repository<User>,
  ) {}

  async createUser(name: string, email: string): Promise<User> {
    const user = this.userRepository.create({ name, email });
    return this.userRepository.save(user);
  }
}
Output
When run, this code creates a new user record in the database with an auto-generated id, name, and unique email.
โš ๏ธ

Common Pitfalls

Common mistakes when creating entities in TypeORM with NestJS include:

  • Forgetting to decorate the class with @Entity(), so TypeORM won't recognize it as a table.
  • Not using @PrimaryGeneratedColumn() or missing a primary key, which is required.
  • Using incorrect types or missing @Column() decorators on properties.
  • Not importing the entity in the TypeOrmModule.forFeature() call in your module, so repository injection fails.
typescript
/* Wrong: Missing @Entity decorator */
import { PrimaryGeneratedColumn, Column } from 'typeorm';

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

  @Column()
  name: string;
}

/* Right: Include @Entity decorator */
import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm';

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

  @Column()
  name: string;
}
๐Ÿ“Š

Quick Reference

Remember these key points when creating entities in TypeORM with NestJS:

  • @Entity(): Marks the class as a database table.
  • @PrimaryGeneratedColumn(): Defines the primary key with auto-increment.
  • @Column(): Defines other columns with optional settings like unique or length.
  • Always import your entities in the module using TypeOrmModule.forFeature([YourEntity]).
โœ…

Key Takeaways

Use @Entity() to mark a class as a database table in TypeORM with NestJS.
Define a primary key with @PrimaryGeneratedColumn() for auto-generated IDs.
Use @Column() to add fields to your entity with optional constraints.
Always register your entity in the module with TypeOrmModule.forFeature().
Avoid missing decorators or incorrect imports to prevent runtime errors.