I'm using mongodb, node.js and backbone.js to build an app that will serve as a learning experience for me. I'm interested to know what is best practice for fetching related objects from a REST API for this sort of thing.
Let's say we have "post" objects and "user" objects, with posts having a "userId" property that links them to users.
Should you:
Does anyone have some experience that they could share?
Thanks
It's hard to answer this without a specific UI story, but based on what you have provided, I'd say #1 is closer to the approach I would take. However, instead of 'inspecting' the post for the userId, provide the link to the user with the rel=user
and simply follow that link for your user resource. I prefer the HATEOAS paradigm where these resources are navigated through explicit links constructed by the server, not the client.
This obviously will result in more XHR's but if that is a concern then I'd suggest that your view is requiring a view model which serves it without joins. This is done by exposing a dedicated model that serves the client simply without making the client responsible for constructing data it needs. hth,
mike
MongoDB does not have a feature to "make the join" on the server, so the relevant question is probably more one of data modelling and whether it makes more sense for you to link or embed the related user data.
Fetch a post object on the client side. Inspect the "userId" property
of the post and then separately fetch that user. This seems to be
nice and simple in terms of server-side code, but could end up making
lots of requests if things get complicated further down the line.
The closest to this option would be fetching the post and then querying for related information for userIDs mentioned in the post using the $in
operator. This may result in slow performance given a large number of userIDs, as effectively the server is still doing a query to look up each userID in the index.
Another common approach to consider is a hybrid option:
embed some minimal user data in the post, for example the userID (a database reference to their user data in another collection) and some details such as their user name.
lookup additional details in an AJAX request as needed (for example, as a hover over the user name).
What works better really depends on your use case and the information you want to display on a page in your application.