From the course: Mastering Nest.js: Build Scalable Applications with Mastery in Nest.js Framework

Unlock this course with a free trial

Join today to access over 25,200 courses taught by industry experts.

Updating a document in MongoDB

Updating a document in MongoDB

Now, let's take a look at how to update a document inside MongoDB using NestJS. Inside the service file, I will create a method named update and pass the ID of type string and the product DTO. We will need these two arguments to make an update. Then I'll give the return await this dot product model dot find by ID and update method. And pass the ID as first argument and the product DTO as second. And to execute the query, I'll give the dot execute method. Let's update the controller as well. I'll give the patch route handler and pass the dynamic ID and an update method which will take the ID param and store it inside the ID property and a request body which will be product DTO. Then first of all, we will check if the ID is valid or not. So I'll bring the same conditional logic which we defined with the find one method, that this is valid condition and paste it here. Next, I'll create a product constant and assign the update method of product service. We'll pass the ID and the product…

Contents