Bird
Raised Fist0
NestJSframework~10 mins

CRUD operations in NestJS - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - CRUD operations
Receive HTTP Request
↓
Route to Controller
↓
Call Service Method
↓
Perform DB Operation
↓
Return Result to Controller
↓
Send HTTP Response
This flow shows how a NestJS app handles CRUD: request comes in, controller routes it, service does DB work, then response goes back.
Execution Sample
NestJS
async create(itemDto) {
  const item = new this.itemModel(itemDto);
  return await item.save();
}
This code creates a new item in the database using a NestJS service method.
Execution Table
StepActionInputProcessOutput
1Receive POST /items{name: 'Book'}Controller routes to create()Call create({name: 'Book'})
2Create new item instance{name: 'Book'}new this.itemModel({name: 'Book'})Item instance created
3Save item to DBItem instanceitem.save()Item saved with _id
4Return saved itemSaved itemReturn to controllerSaved item returned
5Send HTTP responseSaved itemController sends responseHTTP 201 Created with item data
6Receive GET /items/:idid=123Controller routes to findOne(id)Call findOne('123')
7Find item by idid=123this.itemModel.findById('123')Item found or null
8Return found itemItem or nullReturn to controllerItem data or 404 error
9Send HTTP responseItem data or errorController sends responseHTTP 200 OK or 404 Not Found
10Receive PUT /items/:idid=123, updateDtoController routes to update(id, updateDto)Call update('123', updateDto)
11Update item in DBid=123, updateDtothis.itemModel.findByIdAndUpdate('123', updateDto, { new: true })Updated item or null
12Return updated itemUpdated item or nullReturn to controllerUpdated item or 404 error
13Send HTTP responseUpdated item or errorController sends responseHTTP 200 OK or 404 Not Found
14Receive DELETE /items/:idid=123Controller routes to remove(id)Call remove('123')
15Delete item in DBid=123this.itemModel.findByIdAndDelete('123')Deleted item or null
16Return deleted itemDeleted item or nullReturn to controllerDeleted item or 404 error
17Send HTTP responseDeleted item or errorController sends responseHTTP 200 OK or 404 Not Found
18ExitNo more requestsEnd of flowWaiting for next request
💡 No more requests, server waits for new HTTP calls
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 6After Step 7After Step 11After Step 15Final
itemDtoundefined{name: 'Book'}{name: 'Book'}undefinedundefinedundefinedundefinedundefined
itemundefinedItem instance with {name: 'Book'}Saved item with _idundefinedundefinedundefinedundefinedundefined
idundefinedundefinedundefined'123''123''123''123'undefined
foundItemundefinedundefinedundefinedundefinedItem or nullundefinedundefinedundefined
updatedItemundefinedundefinedundefinedundefinedundefinedUpdated item or nullundefinedundefined
deletedItemundefinedundefinedundefinedundefinedundefinedundefinedDeleted item or nullundefined
Key Moments - 3 Insights
Why do we create a new item instance before saving?
Because in step 2, new this.itemModel(itemDto) creates a model instance that has the save() method to store data in the database.
What happens if findById returns null?
As seen in steps 7 and 8, if no item matches the id, the service returns null, and the controller sends a 404 Not Found response.
How does the controller know which service method to call?
In step 1 and others, the HTTP method and route determine which controller method runs, which then calls the matching service method.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table at step 3. What is the output after saving the item?
AAn item saved with a database-generated _id
BAn item instance without an ID
CNull because save failed
DThe original itemDto object
💡 Hint
Check the 'Output' column in step 3 showing 'Item saved with _id'
At which step does the controller send a 404 Not Found response if the item is missing?
AStep 5
BStep 9
CStep 13
DStep 17
💡 Hint
Look at steps 7-9 for GET request handling and response sending
If the updateDto changes the item name, which step reflects the updated item returned?
AStep 15
BStep 7
CStep 11
DStep 3
💡 Hint
Step 11 shows the update operation returning the updated item
Concept Snapshot
CRUD operations in NestJS:
- Controller receives HTTP requests (GET, POST, PUT, DELETE)
- Controller calls Service methods (create, findOne, update, remove)
- Service uses model methods (save, findById, findByIdAndUpdate, findByIdAndDelete)
- Database operations return data or null
- Controller sends HTTP responses accordingly
- Handles success (200/201) and errors (404)
Full Transcript
This visual execution trace shows how CRUD operations work in a NestJS app. When a request comes in, the controller routes it to the right service method. For creating, the service makes a new model instance and saves it to the database. For reading, it finds by ID. For updating, it finds and updates by ID. For deleting, it finds and deletes by ID. Each step returns data or null, and the controller sends the right HTTP response. The variable tracker shows how data changes after each step. Key moments clarify why we create model instances and how missing data leads to 404 responses. The quiz tests understanding of outputs and response steps.

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