Search code examples
mongodbmeteor

How to design 'one to many relation' in Meteor/MongoDB


I am learning Meteor & MongoDB. I wanted to know, how to relation handle in mongo/meteor. I have 2 collections. Teachers and Subjects. One Teacher can have multiple subjects. How to design this relationship using mongo meteor?


Solution

  • You can do it with a relational technique, it is quite common for people to create 2 collections, as you have done. You can add a teacherId to the subjects collection, so that you can have many subjects per teacher.

    If you want to model a many-to-many relationship, the relational model wants to use a linkage entity, ie a small table that refers to both teacher and subject. A way to do this in mongo is for one of the collections to have an array of references, so for example subjects can contain a 'teacherIds` field, which is an array of teacher id's.

    If the subjects don't really have any additional data, you can just create an array of subjects within teacher. These can be a simple string, or an object if more data is required.