Reputation: 1481
In my app, users have events and groups - and events can (but don't need to) belong to groups. I'm still new to non-relational DBs, so I'd like to know best practices for optimally structuring this.
var user = new mongoose.Schema({
name: { type: String },
events: [event],
groups: [group]
});
var group = new mongoose.Schema({
name: { type: String }
});
This is where I'm confused.
var event = new mongoose.Schema({
name: { type: String }
groups: ????
});
Do I just keep an array with references to the id of group?
If I do that, how would I find events by group?
And if a group is deleted, would I have to iterate over each event to remove the reference?
Upvotes: 1
Views: 2168
Reputation: 2984
In mongodb, you have two choices. Embedding (subdocument) Vs Linking (another collection)
Embedding Vs Linking There are pros and cons with each approach.
Embedding: You nest it inside the document.
for instance, your document might look like
{
name : 'name',
events: [a,b,c],
groups: [1,2,3]
}
Linking
Here you link with a kind of Foreign key. Refer to docs
Documents in one collection will reference documents in another collection. Disadvantage is that you lose atomic operations. However, you eliminate duplication.
If you want to update groups, and update events, and they are in separate collections, you'll have to handle atomic updates yourself. Mongodb will not guarantee it for you.
Upvotes: 5