Suppose I have Student and Teacher in a many to many relationship. If I just want to find out all the teachers for a given student or vice versa I generally model it by using embedded Object Ids. For example if teacher has a property studentIds which is an array of student Object Ids then that is enough information to do all the queries you need.
However suppose that a student can give a teacher a rating. How should this rating fit into the model? At the moment I do the following:
- Inside teacher instead of storing an array of student, I store an array of json objects {studentId: ObjectId, rating: String}
- When doing the query, I transform the array of json objects into an array of studentIds and extract the full information as usual
- So now I have an array of student objects and an array of json objects with the ratings
- However, since the $in operator in MongoDB does not preserve ordering, I need to do my own sorting
- At the last step, with everything in order I can combine student objects with ratings to get what I want
It works but seems somewhat convoluted is there a better way of doing this?