TypeORM Integration & Entities
TypeORM Integration & Entities
Most real applications need a database. TypeORM is the most popular ORM for NestJS — it maps TypeScript classes to database tables, so you work with objects instead of raw SQL. NestJS provides a dedicated @nestjs/typeorm package that integrates it cleanly with modules and dependency injection.
Connecting to the database
Install the packages and configure the connection once with TypeOrmModule.forRoot() in your root module:
Defining an entity
An entity is a class decorated with @Entity(); its columns are properties decorated with column decorators:
Common column decorators
@PrimaryGeneratedColumn()— an auto-incrementing primary key (or'uuid'for a UUID).@Column()— a regular column, with options liketype,length,nullable,unique,default.@CreateDateColumn()/@UpdateDateColumn()— automatic timestamps.@Index()— add a database index for faster lookups.
Registering the entity in a feature module
To use an entity's repository inside a feature, register it with forFeature():
This makes a Repository<User> injectable in that module — which is how you query and save users, covered in the next lesson.
forRoot() configures the database connection once (root module); forFeature() registers specific entities' repositories for the modules that need them. You will recognise this dynamic-module pattern from earlier.
Async configuration
In a real app the connection details come from config, not hard-coded values. Use forRootAsync() to inject ConfigService:
Summary
TypeORM maps classes to tables. Configure the connection with TypeOrmModule.forRoot() (or forRootAsync() with config), define entities using @Entity() and column decorators, and register them per-feature with forFeature(). Keep synchronize off in production. Next we use the repository this generates to read and write data.