Embedding collections (subdocument arrays) with MongoDB violates REST?

320 views Asked by At

Let's say I have a users collection in my Mongo database:

users
  _id
  emailAddress
  firstName
  lastName
  passwordHash
  accessLogs: [ ... ]
  createdAt

As you can see, a user document can contain an array of accessLogs. Great.

But let's say I want to update a user record and do a PUT /users/:id request against my RESTful API that uses this database. With a PUT, you're supposed to get back what you put in. So let's say the user has logged in 500 times. In order to avoid violating REST, does this mean my PUT data should include the accessLogs array and all its items?

I suppose the request handler could just update everything except accessLogs.

2

There are 2 answers

0
Explosion Pills On

In the strictest definition PUT should indeed replace the contents of the object. If you want to update an existing object with partial data/instructions instead, you should use the PATCH method. This would allow you to specify that you want to add accessLogs (or otherwise leave them unmodified) and not have to send the entire object -- just instructions for what needs to be updated.

0
inf3rno On

In your case the accessLogs is a generated read-only property and so it does not have to be part of your PUT request. You don't send the _id property as well and if some of the properties have default values, you don't have to send those either.

The PUT method requests that the enclosed entity be stored under the supplied Request-URI. If the Request-URI refers to an already existing resource, the enclosed entity SHOULD be considered as a modified version of the one residing on the origin server.

The difference between the PUT and PATCH requests is reflected in the way the server processes the enclosed entity to modify the resource identified by the Request-URI. In a PUT request, the enclosed entity is considered to be a modified version of the resource stored on the origin server, and the client is requesting that the stored version be replaced. With PATCH, however, the enclosed entity contains a set of instructions describing how a resource currently residing on the origin server should be modified to produce a new version. The PATCH method affects the resource identified by the Request-URI, and it also MAY have side effects on other resources; i.e., new resources may be created, or existing ones modified, by the application of a PATCH.

You can find a similar question here.