Creating sub-documents in Mongoose models

Sub-documents are a common way to compose a child model into a parent model's schema. Consider, for example, the creation of an order record in an e-commerce system. This record would contain references to a user model, a list of product models, and a payment and shipping model. In an SQL database, each of these entities would have a referenced ID within their own normalized table, using several JOIN operations to merge the necessary parts together into this new order model construct. By default, MongoDB approaches this problem radically differently, with the entirety of the schema simply embedding the sub-document references directly into its own order schema definition.

This approach is a trade-off. It gives you expressive, flexible JSON model representations that remain performant while still allowing rich querying and searching capabilities. However, the loss is that embedded data is written in place without being updated when values change outside itself. In practice, this makes sub-documents best for modeling many-to-one relationships. Think of items such as comments, on a blog post. There can be many comments, but they can only relate to a single blog post. Such a relationship can be effectively handled as a sub-document relationship in MongoDB.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.226.222.162