Search⌘ K
AI Features

Many-to-Many Relationships in MongoDB

Explore how to model many-to-many relationships in MongoDB by linking documents on both sides with string ID references. Understand using $lookup to join data across collections, the trade-offs between one-sided and two-sided references, and practical design decisions for maintaining data consistency in MERN applications.

Many-to-many is the most involved relationship type. Unlike one-to-many, where the link sits on a single side, here each side relates to many of the other: a feature like tags, followers, permissions, or, in this course, the link between orders and products. One order includes several products, and one product is purchased across many orders. This lesson models that relationship using the data's string-id references and joins it with $lookup.

Note: Mongoose's populate() can resolve many-to-many links when both sides store arrays of ObjectId values with a ref. This course references by the string id (an order's items hold productId strings like "2049"), so $lookup is the technique that works against the seeded data. populate() is the equivalent when ObjectId references are used.

To make the relationship concrete, the next visual should show ... ...