Creating relational documents in MongoDB with population
Having an objectId reference can be useful. However, we often want to return a whole model as if it were an embedded sub-document, but have it contain the updated data from the referenced document. This operation is possible using Mongoose's populate
method. With populate, we can retrieve the additional document details required, similar to a JOIN
operation in a relational database, and merge the result into the referencing document.
Getting ready
Let's update our /middleware/rest.js
middleware to support Mongoose population for retrieving documents that contain embedded objectId references. We will be able to retrieve our full post details in our /api/users/<user id>
API endpoint requests by populating the included posts property on our user document.
How to do it...
Let's follow these steps to learn how to populate our user's blog post list with their blog post content:
- First, we will need to restructure our
/middleware/rest.js
...