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.

Deleting a document from MongoDB

Deleting a document from MongoDB

Now, let's see how to delete a document from the collection. Inside the service file, I'll create a delete method and pass the ID parameter of type string. And I will return await this.productModel.findById and delete will pass the ID.execute. So this is going to delete the document from the collection based on the document ID. Now inside the controller, I'll give the delete route handler and pass the dynamic ID. Creating a delete method, passing the param decorator to get the ID value, and we'll store it inside the ID property of type string. Then again, we will need the ID validation logic. So I'll quickly bring the same validation logic here in the delete method as well. Next I'll create a product constant and assign the delete method from product service and pass the ID. And we will return the product. Let's save this and check the output. I'll select the delete request type and set the route path. Let's delete the first product that is Apple. So I'll copy the ID and paste it…

Contents