Hey there I am working on a schema design where some users create digital courses and others can buy them - think of it like Udemy. I am having trouble deciding on the best way of storing the bought courses so the fetch queries are efficient.
- Option - store references of courses a user buys with a date in a
boughtCourses
array inside the user document. The array in the User model would look like this:
{
...
boughtCourses: [ { enrolledAt: Date, course: ReferenceID }, { enrolledAt: Date, course: ReferenceID } ]
}
This approach is straightforward but can lead to an unbound array issue (really small chance tho). I would use populate from mongoose to get the referenced data. Implementing pagination with filtering and also providing the total number of documents may not be that efficient for a large number of documents.
- Option - I would prepare a separate collection named
CourseEnrollment
which would hold the enrollment information for all courses. Each document would look something like this:
{
course: CourseID;
buyer: BuyerID;
seller: SellerID;
createdAt: Date;
}
To fetch the courses of a user I would create an index on the buyer field and fetch them by it. However I am not sure about the large number of documents over time that would appear in the collection as every buy would insert a new document inside. Fetching the bought courses may be easier however the size of the collection may become to much to include it in the cache.
Which option would you say is better?