Bird
Raised Fist0
NestJSframework~20 mins

Repository pattern in NestJS - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Repository Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What is the output of this NestJS repository method call?
Consider a NestJS repository method that fetches all users with the role 'admin'. What will be the output if the database contains 3 users with roles: 'admin', 'user', 'admin'?
NestJS
async findAdmins() {
  return this.userRepository.find({ where: { role: 'admin' } });
}
AAn array with 2 user objects having role 'admin'
BAn array with all 3 user objects regardless of role
CAn empty array
DA single user object with role 'admin'
Attempts:
2 left
💡 Hint
Remember that the find method returns all matching records as an array.
📝 Syntax
intermediate
2:00remaining
Which option correctly defines a custom repository method in NestJS?
You want to add a method 'findByEmail' to your UserRepository to find a user by email. Which code snippet correctly defines this method?
A
async findByEmail(email: string) {
  return this.findOneBy({ email });
}
B
async findByEmail(email: string) {
  return this.userRepository.findOneByEmail(email);
}
C
async findByEmail(email: string) {
  return this.userRepository.findOne({ email });
}
D
async findByEmail(email: string) {
  return this.findOne({ where: { email } });
}
Attempts:
2 left
💡 Hint
Check the correct TypeORM repository method for finding one record by condition.
🔧 Debug
advanced
2:00remaining
Why does this NestJS repository method throw a runtime error?
Given the method below, why does calling 'findUserById(5)' throw an error?
NestJS
async findUserById(id: number) {
  return this.userRepository.findOne({ where: { id } });
}
AThe method findOne is deprecated and cannot be used
BThe id parameter must be a string, not a number
CfindOne expects an object with conditions, not a direct id argument
DThe repository is not injected properly
Attempts:
2 left
💡 Hint
Check the TypeORM repository method signatures for findOne.
❓ state_output
advanced
2:00remaining
What is the state of the database after this repository save operation?
If you call this method to save a user object with id 10 and name 'Alice', what happens if a user with id 10 already exists?
NestJS
async saveUser(user: User) {
  return this.userRepository.save(user);
}

// Called with { id: 10, name: 'Alice' }
AThe existing user remains unchanged
BA new user with id 10 is created, causing a duplicate key error
CThe save method throws a runtime error
DThe existing user with id 10 is updated with name 'Alice'
Attempts:
2 left
💡 Hint
The save method updates if primary key exists, otherwise inserts.
🧠 Conceptual
expert
2:00remaining
Which statement best describes the role of the repository pattern in NestJS?
Choose the most accurate description of why the repository pattern is used in NestJS applications.
AIt automatically generates REST API endpoints for database entities
BIt abstracts data access logic, allowing business logic to remain independent of database details
CIt replaces the need for service classes in NestJS
DIt enforces strict typing on all database queries
Attempts:
2 left
💡 Hint
Think about separation of concerns between data access and business logic.

Practice

(1/5)
1. What is the main purpose of the Repository pattern in NestJS?
easy
A. To separate data access logic from business logic
B. To handle HTTP requests directly
C. To manage application configuration settings
D. To create UI components

Solution

  1. Step 1: Understand the role of Repository pattern

    The Repository pattern is designed to isolate data access logic from the rest of the application.
  2. Step 2: Identify what Repository does in NestJS

    In NestJS, repositories handle database operations, keeping business logic clean and testable.
  3. Final Answer:

    To separate data access logic from business logic -> Option A
  4. Quick Check:

    Repository pattern = separate data access [OK]
Hint: Repository = data access layer, not UI or config [OK]
Common Mistakes:
  • Confusing repository with controller responsibilities
  • Thinking repository manages UI or HTTP directly
  • Mixing repository with configuration management
2. Which of the following is the correct way to inject a repository in a NestJS service using TypeORM?
easy
A. @Inject(UserRepository) private userRepository: Repository<User>;
B. @InjectableRepository(User) private userRepository: Repository<User>;
C. @RepositoryInject(User) private userRepository: Repository<User>;
D. @InjectRepository(User) private userRepository: Repository<User>;

Solution

  1. Step 1: Recall the correct decorator for repository injection

    In NestJS with TypeORM, @InjectRepository() is used to inject repositories.
  2. Step 2: Match the syntax with the correct option

    @InjectRepository(User) private userRepository: Repository<User>; uses @InjectRepository(User) which is the official and correct syntax.
  3. Final Answer:

    @InjectRepository(User) private userRepository: Repository<User>; -> Option D
  4. Quick Check:

    @InjectRepository = correct injection [OK]
Hint: Use @InjectRepository to inject TypeORM repositories [OK]
Common Mistakes:
  • Using wrong decorator names like @InjectableRepository
  • Confusing @Inject with @InjectRepository
  • Omitting the entity inside @InjectRepository()
3. Given the following NestJS service code, what will findAll() return?
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from './user.entity';

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

  async findAll() {
    return await this.userRepo.find();
  }
}
medium
A. Undefined, because find() is not a valid method
B. A single User entity
C. An array of all User entities from the database
D. A Promise that resolves to null

Solution

  1. Step 1: Understand what this.userRepo.find() does

    The find() method of TypeORM repository returns all records of the entity as an array.
  2. Step 2: Analyze the return type of findAll()

    Since find() returns a Promise resolving to an array of User entities, findAll() returns that array.
  3. Final Answer:

    An array of all User entities from the database -> Option C
  4. Quick Check:

    Repository.find() returns array [OK]
Hint: Repository.find() returns all records as an array [OK]
Common Mistakes:
  • Thinking find() returns a single entity
  • Assuming find() is not a valid method
  • Confusing Promise with null return
4. Identify the error in this NestJS repository injection code snippet:
@Injectable()
export class ProductService {
  constructor(private productRepository: Repository<Product>) {}
}
medium
A. Missing @InjectRepository decorator for productRepository
B. Repository should be injected using @InjectableRepository
C. Constructor should not have parameters
D. Repository cannot be injected in services

Solution

  1. Step 1: Check how repositories are injected in NestJS

    Repositories must be injected with @InjectRepository(Entity) decorator to work properly.
  2. Step 2: Identify missing decorator in the code

    The code misses @InjectRepository(Product) before the repository parameter.
  3. Final Answer:

    Missing @InjectRepository decorator for productRepository -> Option A
  4. Quick Check:

    Repository injection needs @InjectRepository [OK]
Hint: Always use @InjectRepository for repositories in constructor [OK]
Common Mistakes:
  • Forgetting @InjectRepository decorator
  • Using wrong decorator names
  • Assuming repositories inject automatically without decorators
5. You want to create a custom method findActiveUsers() in your UserRepository that returns only users with isActive = true. Which approach correctly applies the Repository pattern in NestJS?
hard
A. Add findActiveUsers() method directly in the UserService without modifying repository
B. Extend the Repository class and add findActiveUsers() method, then inject this custom repository
C. Use a global function outside repository and service to filter active users
D. Modify the User entity to include a static method findActiveUsers()

Solution

  1. Step 1: Understand extending repository for custom methods

    To add custom queries, extend the Repository class and add methods like findActiveUsers().
  2. Step 2: Confirm proper injection of custom repository

    Inject the custom repository in services to keep data access logic encapsulated.
  3. Final Answer:

    Extend the Repository class and add findActiveUsers() method, then inject this custom repository -> Option B
  4. Quick Check:

    Custom repo methods = extend Repository [OK]
Hint: Add custom queries by extending Repository class [OK]
Common Mistakes:
  • Putting query logic in service instead of repository
  • Using global functions outside repository pattern
  • Adding static methods to entity instead of repository
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard