API with NestJS #49. Updating with PUT and PATCH with MongoDB and Mongoose

JavaScript MongoDB NestJS

This entry is part 49 of 121 in the API with NestJS

When we develop a REST API, there is a set of HTTP methods that we can choose from, such as GET, POST, and DELETE. A crucial thing to understand is that HTTP methods are largely conventional. It is our job to make them work in a way that’s consistent with the specification. For example, in theory, we could delete entities with the GET method. However, we should make our API predictable to make it easy to understand both to developers working on our backend and the users.

A lot of HTTP methods are very straightforward. However, the PUT and PATCH methods are worth digging into a bit more. In this article, we compare both of them and implement them with NestJS and Mongoose.

PUT

The PUT method is responsible for modifying an existing entity. The crucial part about it is that it is supposed to replace an entity. Therefore, if we don’t send a field of an entity when performing a PUT request, the missing field should be removed from the document.

Above, we can see the properties our post contains. Let’s make a PUT request now.

The crucial thing above is that we didn’t send the property in the body of our request. Because the PUT method is supposed to replace a whole entity, we’ve deleted the property.

Implementing the PUT method with MongoDB and Mongoose

There are quite a few ways of implementing a proper PUT method with MongoDB and Mongoose. The and methods are common, but they don’t replace the whole document by default. Instead, they perform a partial update on it. Because of that, not including a property in the body of the request does not remove it. We can fix that with the option.

posts.service.ts

By setting , we indicate that we want the method to return the modified version of the document.

posts.controller.ts

Thanks to doing the above, when we update a document, we replace it as a whole and remove not included fields.

We could also use the method. Not so long back, it wasn’t included with the TypeScript definitions shipped with the , unfortunately. Thankfully, the Mongoose team started working on official TypeScript definitions. They released it in version v5.11.0.

posts.service.ts

createPost.dto.ts

Preventing the id from being updated

Since we expect the users to send the whole document, they also send the property. The above doesn’t cause any issues as long as the user doesn’t alter the id. That’s because doing that can cause an unexpected error:

MongoError: Plan executor error during findAndModify :: caused by :: After applying the update, the (immutable) field ‘_id’ was found to have been altered

We can deal with the above error by excluding the property from the body of our PUT request.

Even if the user provides the property in the request, we exclude it and don’t pass it to the or the methods. Rest assured, because MongoDB won’t remove the property in such a case, even though we are implementing the PUT method here.

PATCH

While the PUT method is a common and valid choice, it might not fit every situation. For example, when implementing the PUT method, we assume that the API users know all of the details of a particular entity. Since omitting single property results in removing it, they need to be careful. A solution to this issue can be the PATCH method.

The PATCH method was introduced to the HTTP protocol in 2010 and aimed to apply a partial modification to an entity. The specification describes it as a set of instructions describing how a resource should be modified. The most straightforward way of implementing the PATCH method is to handle a body with a partial document.

The above request modifies the post by changing the title and removing the property. Please note that to delete a field, we need to send the value explicitly. Thanks to this, no fields are deleted by accident.

Implementing PATCH with MongoDB and Mongoose

To implement a PATCH handler using Mongoose, we can use the method without the option. First, let’s use the decorator in our controller:

posts.controller.ts

Now, let’s modify the service:

posts.service.ts

For the above to work correctly, we also need to modify our DTO by adding the decorators:

updatePost.dto.ts

Thanks to adding the decorators, the user no longer has to provide all of the document’s properties.

JSON Patch

An alternative approach to our implementation is to quite literally send a set of instructions on how to modify an object. A way to do that is to use the JSON Patch format.

If you want to know more, check out the jsonpatch.com website. Additionally, the fast-json-patch library might come in handy when implementing the above format into your application.

Summary

In this article, we’ve learned about various ways of implementing the update functionality. Thanks to getting to know both about PUT and PATCH, we can choose the best approach for a particular case. When selecting one of the above, we should follow the specification and implement our API predictably and transparently. If we do that, we will make the life of our teammates and API users easier.

Series Navigation<< API with NestJS #48. Definining indexes with MongoDB and MongooseAPI with NestJS #50. Introduction to logging with the built-in logger and TypeORM >>
Subscribe
Notify of
guest
2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Aayush Taneja
3 years ago

In the patch request, what if the client sends null for a non-nullable field? How do we describe in the DTO schema if a field is not nullable?

catato
catato
2 years ago
Reply to  Aayush Taneja

Something lie this?