Bird
Raised Fist0
NestJSframework~20 mins

CRUD operations in NestJS - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
NestJS CRUD Master
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 controller method?
Consider this NestJS controller method that handles a GET request to fetch all items. What will be the HTTP response body when this method is called?
NestJS
import { Controller, Get } from '@nestjs/common';

@Controller('items')
export class ItemsController {
  @Get()
  findAll() {
    return ['apple', 'banana', 'cherry'];
  }
}
AHTTP 200 with JSON body: ["apple", "banana", "cherry"]
BHTTP 500 Internal Server Error
CHTTP 404 Not Found error
DHTTP 200 with empty JSON array []
Attempts:
2 left
💡 Hint
The method returns a simple array directly.
❓ state_output
intermediate
2:00remaining
What is the value of the 'items' array after these service calls?
Given this NestJS service managing an in-memory list, what is the content of the 'items' array after executing the code below?
NestJS
export class ItemsService {
  private items = ['a', 'b'];

  addItem(item: string) {
    this.items.push(item);
  }

  removeItem(item: string) {
    this.items = this.items.filter(i => i !== item);
  }

  getItems() {
    return this.items;
  }
}

const service = new ItemsService();
service.addItem('c');
service.removeItem('a');
const result = service.getItems();
A["a", "b", "c"]
B["c"]
C["a", "b"]
D["b", "c"]
Attempts:
2 left
💡 Hint
Adding 'c' then removing 'a' affects the array.
📝 Syntax
advanced
2:00remaining
Which option causes a syntax error in this NestJS controller method?
Identify the option that will cause a syntax error when defining a POST method in a NestJS controller.
NestJS
import { Controller, Post, Body } from '@nestjs/common';

@Controller('users')
export class UsersController {
  @Post()
  createUser(@Body() userData) {
    return userData;
  }
}
A
}
;ataDresu nruter  
{ )ataDresu )(ydoB@(resUetaerc
)(tsoP@
B
@Post()
createUser(@Body() userData) {
  return userData;
}
C
@Post()
createUser(@Body userData) {
  return userData;
}
D
@Post()
createUser(@Body() userData) {
  return userData
}
Attempts:
2 left
💡 Hint
Check the decorator syntax carefully.
🔧 Debug
advanced
2:00remaining
Why does this NestJS service method throw a runtime error?
This service method is supposed to update an item by id. Why does it throw an error when called?
NestJS
export class ItemsService {
  private items = [{ id: 1, name: 'a' }, { id: 2, name: 'b' }];

  updateItem(id: number, newName: string) {
    const item = this.items.find(i => i.id === id);
    item.name = newName;
  }
}

const service = new ItemsService();
service.updateItem(3, 'c');
AReferenceError: item is not defined
BTypeError: Cannot set property 'name' of undefined
CNo error, item updated successfully
DSyntaxError: Unexpected token '='
Attempts:
2 left
💡 Hint
What happens if find() returns undefined?
🧠 Conceptual
expert
2:00remaining
Which option correctly describes the role of DTOs in NestJS CRUD operations?
In NestJS, Data Transfer Objects (DTOs) are often used in CRUD operations. Which statement best describes their purpose?
ADTOs define the shape of data sent over the network and help validate input before processing.
BDTOs are used to directly access the database without services.
CDTOs automatically generate database tables based on controller methods.
DDTOs replace controllers and handle HTTP requests themselves.
Attempts:
2 left
💡 Hint
Think about how data is structured and validated in NestJS.

Practice

(1/5)
1. In NestJS, which decorator is used in a controller method to handle HTTP POST requests for creating data?
easy
A. @Post
B. @Get
C. @Put
D. @Delete

Solution

  1. Step 1: Understand HTTP methods and their NestJS decorators

    HTTP POST is used to create new data. NestJS uses @Post decorator for this.
  2. Step 2: Match the decorator to the HTTP method

    @Get is for reading, @Put for updating, and @Delete for deleting data, so they don't fit creating data.
  3. Final Answer:

    @Post -> Option A
  4. Quick Check:

    POST = @Post [OK]
Hint: POST requests use @Post decorator in NestJS controllers [OK]
Common Mistakes:
  • Confusing @Get with @Post
  • Using @Put for creating data
  • Using @Delete for creation
2. Which of the following is the correct way to extract a route parameter named id in a NestJS controller method?
easy
A. async getItem(@Body('id') id: string) {}
B. async getItem(@Query('id') id: string) {}
C. async getItem(@Param('id') id: string) {}
D. async getItem(@Headers('id') id: string) {}

Solution

  1. Step 1: Identify the decorator for route parameters

    @Param is used to extract parameters from the URL path, such as /items/:id.
  2. Step 2: Check other decorators and their uses

    @Body extracts data from the request body, @Query from query strings, and @Headers from HTTP headers, so they don't get route params.
  3. Final Answer:

    async getItem(@Param('id') id: string) {} -> Option C
  4. Quick Check:

    Route param = @Param [OK]
Hint: Use @Param to get URL parameters in NestJS [OK]
Common Mistakes:
  • Using @Body to get URL params
  • Using @Query for route params
  • Confusing @Headers with @Param
3. Given this NestJS controller method, what will be the response if a client sends a DELETE request to /items/5 and the service deletes the item successfully?
  @Delete(':id')
  async remove(@Param('id') id: string) {
    await this.itemsService.delete(id);
    return { message: `Item ${id} deleted` };
  }
medium
A. HTTP 404 Not Found
B. { "message": "Item 5 deleted" }
C. { "error": "Item not found" }
D. Empty response with HTTP 204 No Content

Solution

  1. Step 1: Analyze the controller method's return value

    The method returns an object with a message string including the id parameter.
  2. Step 2: Understand the response for successful deletion

    Since the method returns a JSON object with the message, the client receives that JSON with HTTP 200 OK by default.
  3. Final Answer:

    { "message": "Item 5 deleted" } -> Option B
  4. Quick Check:

    Return JSON message on success = { "message": "Item 5 deleted" } [OK]
Hint: Returned object becomes JSON response by default in NestJS [OK]
Common Mistakes:
  • Expecting HTTP 204 No Content without explicit status
  • Assuming error response without checking service
  • Confusing DELETE with GET response
4. Identify the error in this NestJS controller method for updating an item:
  @Put(':id')
  async update(@Body() updateDto: UpdateItemDto) {
    return this.itemsService.update(updateDto.id, updateDto);
  }
medium
A. Method should be named create, not update
B. Using @Body instead of @Query for update data
C. UpdateItemDto cannot be used in @Body
D. Missing @Param decorator to get the id from URL

Solution

  1. Step 1: Check how the id is obtained

    The method expects id from updateDto.id, but the route has ':id' parameter which is not extracted.
  2. Step 2: Identify missing @Param decorator

    To get id from URL, @Param('id') id: string should be added as a parameter to the method.
  3. Final Answer:

    Missing @Param decorator to get the id from URL -> Option D
  4. Quick Check:

    URL param needs @Param [OK]
Hint: Use @Param to get URL id in update methods [OK]
Common Mistakes:
  • Assuming id comes from body without @Param
  • Confusing @Body with @Query
  • Ignoring route parameters
5. You want to implement a NestJS controller method to update an item by its id from the URL and new data from the request body. Which of the following method signatures correctly follows NestJS CRUD patterns?
hard
A. async update(@Param('id') id: string, @Body() updateDto: UpdateItemDto) { return this.itemsService.update(id, updateDto); }
B. async update(@Body('id') id: string, @Body() updateDto: UpdateItemDto) { return this.itemsService.update(id, updateDto); }
C. async update(@Query('id') id: string, @Body() updateDto: UpdateItemDto) { return this.itemsService.update(id, updateDto); }
D. async update(@Param() params: any) { return this.itemsService.update(params.id, params); }

Solution

  1. Step 1: Identify correct decorators for id and body

    Use @Param('id') to get id from URL and @Body() to get update data object.
  2. Step 2: Check method parameters and service call

    async update(@Param('id') id: string, @Body() updateDto: UpdateItemDto) { return this.itemsService.update(id, updateDto); } correctly separates id and updateDto and calls service with both.
  3. Final Answer:

    async update(@Param('id') id: string, @Body() updateDto: UpdateItemDto) { return this.itemsService.update(id, updateDto); } -> Option A
  4. Quick Check:

    Use @Param for id, @Body for data [OK]
Hint: Use @Param('id') and @Body() together for update methods [OK]
Common Mistakes:
  • Using @Body('id') instead of @Param('id')
  • Using @Query for route params
  • Passing params object instead of separate arguments
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