Exercises
Objectives
By the end of this lesson, you should be able to:
- Model the same relationship two different ways, embedded and referenced
- Justify, in writing, which real-world relationships should use each approach
- Load referenced data with
populate, and embedded data with a single query
⚠️ A note on verification: as throughout the MongoDB half of this course, this tooling has no route to a local MongoDB server, so the expected output below reflects Mongoose’s stable, documented behavior rather than this course’s own live execution. Run every step yourself, on your own machine, against a real MongoDB server.
Exercise: An Online Course Platform
a) Model it. Design schemas for a small course platform:
Course(title,description)Lesson, embedded insideCourse(title,content), since a lesson only ever exists as part of one courseInstructor, referenced fromCourse(name,bio), since the same instructor teaches many coursesEnrollment, referencing both aStudentand aCourse(enrolledAt), since enrollments are queried independently, “show all of a student’s enrollments,” “show all enrollments for a course”
b) Justify each choice. For Lesson, Instructor, and Enrollment, write one sentence each explaining why it was embedded or referenced, using the questions from Lesson 3.
c) Create a course with embedded lessons. In one Course.create() call, create a course with two embedded lessons.
d) Create a referenced instructor. Create an Instructor, then create a second course referencing that same instructor’s _id.
e) Populate it. Fetch a course with .populate('instructor'), and confirm the full instructor document appears nested, not just an ID.
f) Query enrollments independently. Create two Enrollment documents referencing the same course but different students, then query all enrollments for that one course, without touching the Course document at all, confirming referencing supports exactly this kind of independent query, which embedding wouldn’t.
g) One paragraph. Explain, in your own words, why Lesson was embedded but Enrollment was referenced, even though both relate to Course.
Recap
This module covered MongoDB’s two ways of modeling relationships, embedding for data that’s exclusive and always read together, referencing (with populate) for data that’s shared or queried independently, and the judgment needed to choose correctly for a given relationship.
Next module: the capstone, rebuilding a full MVC-structured Express app on top of a real database instead of an in-memory array.