We have a one-to-many relationship stored as two separate collections in MongoDB. The relationship is: 1 Team has many People. We are intentionally saving these as separate collections because we want to be able to query them separately. We decided on this design after doing bunch of research - I hope it makes sense. Here are the simplified Mongoose schemas:
var TeamSchema = new Mongoose.Schema({
name: String
});
var PersonSchema = new Mongoose.Schema({
name: String
teamId: {
type: Mongoose.Schema.ObjectId,
ref: 'Team',
}
});
I would like to join the two collections as follows before sending them to the front-end:
[
{ "name": "John Doe", "Team": "Orange" },
{ "name": "Jane Smith", "Team": "Orange" },
{ "name": "Doug White", "Team": "Blue" }
]
I don't mind doing two separate queries to get each collection into memory. The question is what's the most efficient way to join the collections once I have them in memory?
This is what I started doing, but the join code is not there:
Person.find(function(err, people) {
Team.find(function(err, teams) {
// Now I have people and teams
// How to join them?
});
});