Creating embedded documents in MongoDB with objectId
Sometimes, there is no substitute for a genuine multi-document relationship in your models. The main method for accomplishing this in MongoDB is through objectId references. These allow for implementation of one-to-one, one-to-many, and many-to-many relationships through reference IDs in models. This type of relationship is very common in web applications. Consider, for instance, our blog post and user relationship. While we could embed the user as a sub-document, if the user ever changes their name, our blog post would still show the name they had when they originally authored the blog post. A true relationship is the best way to model these separate documents.
Getting ready
Let's implement an objectId reference relationship between our user model and blog post model. We'll extend our API to include a /api/users
endpoint that will allow us to work with users in the same way as our blog posts.
How to do it...
Let's follow these steps to add...