We use MongoDB and we provide restful api to access resources (not only collections). For example I have a devices collection. Every device document has an embedded array: carriers. These are association classes for carriers, without any unique id.
{
_id: ObjectId("..."),
carriers: [
{
carrier: ObjectId("..."),
bindingInterval: {
from: ISODate("..."),
to: ISODate("...")
}
},
...
]
}
In our service the uniqueness of carrier-binding determined by a compound of specific fields: carrier + from + to values.
Question: What is the best restful practice to require these embedded documents? In many cases I GET / POST / PUT / DELETE them individually.
Otherwise it's just an example. We have embedded documents in many other cases.
Ideas:
As far as I understood you need to access the elements that are not assigned with any ID in a RESTful way.
First of all I'd add a separate endpoint for the carriers only. It will be:
/devices/{deviceID}/carriers/
I don't know why not assign an unique ID on mongo DB level (this seems to be the easiest option) but if it's not possible it's better to refer a given resource via an artificial compound key passed in path rather than sending the parameters separately via query string. So each time you return the collection of carriers assign each element a:
carrierID = md5(carrier+from+to)
With such a key you can easily refer every embedded resource via:
/devices/{deviceID}/carriers/{carrierID}/
It seems that it will be much easier to refer such resources via different endpoints.
The downside is that you need to recalculate the carrierID
for all resources on the backend side to check if any of them matches the received one.
I see that you've an ObjectId
for each carrier field. Isn't it unique? Why don't you use it?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With