Complete the code to import the TypeORM module in a NestJS module.
import { Module } from '@nestjs/common'; import { TypeOrmModule } from '[1]'; @Module({ imports: [TypeOrmModule.forRoot()], }) export class AppModule {}
TypeORM is integrated into NestJS via the @nestjs/typeorm package, which provides the module to connect TypeORM with NestJS.
Complete the code to register an entity with TypeORM in a NestJS module.
import { Module } from '@nestjs/common'; import { TypeOrmModule } from '@nestjs/typeorm'; import { User } from './user.entity'; @Module({ imports: [TypeOrmModule.forFeature([[1]])], }) export class UsersModule {}
Entities like User must be registered in the forFeature method to be used in repositories within the module.
Fix the error in the service constructor to inject the repository correctly.
import { Injectable } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { Repository } from 'typeorm'; import { User } from './user.entity'; @Injectable() export class UsersService { constructor( private readonly [1] repository: Repository<User>, ) {} }
To inject a repository, use the @InjectRepository(Entity) decorator before the parameter.
Fill both blanks to configure TypeORM connection options in NestJS.
TypeOrmModule.forRoot({
type: '[1]',
host: '[2]',
port: 5432,
username: 'user',
password: 'pass',
database: 'testdb',
entities: [__dirname + '/**/*.entity{.ts,.js}'],
synchronize: true,
})The type option specifies the database type, here 'postgres'. The host is usually 'localhost' for local development.
Fill all three blanks to create a repository method that finds a user by email.
async findByEmail([1]: string): Promise<User | null> { return this.userRepository.[2]({ where: { [3] } }); }
The method parameter is email. The repository method to find one record is findOne. The query condition uses email as the key.