Search⌘ K
AI Features

Using ObjectId, ref, and Cross-Model References

Explore how to model and resolve cross-collection references in MongoDB using ObjectId, ref, and $lookup. Understand how to join documents from multiple collections safely, avoid exposing sensitive fields during joins, and prevent circular references in MERN stack applications.

The previous lessons modeled one-to-many and many-to-many relationships. This lesson focuses on how references are stored and resolved: a single document referencing documents in multiple other collections, the joins that resolve those references, and the mistakes that can turn a working join into a security issue or performance problem. The running example is a review document, which references both the reviewed product and the user who wrote the review.

Note: Mongoose's populate() resolves references when a field is an ObjectId paired with a ref to another model, and it can nest (populate within populate) and take a field list to limit what is returned. This course references the string id (reviews.userId holds "0030", reviews.productId holds "2007"), so $lookup and $project are the equivalents that work against the seeded data.

To make the references concrete, the next visual should ... ...