Reputation: 329
I have two collections in my mongodb database :- Users , Clubs
User Schema :-
var UserSchema = new Schema({
Name: {
type: String ,
required: true
},
Clubs: [
{type: mongoose.Schema.Types.ObjectId, ref: 'Club'}
]});
Now when a user joins a club , i update the club array . But I also frequently need to fetch all the users for a particular club . Therefore I am creating the club schema as :-
var ClubSchema = new Schema({
clubName : {
type: String ,
unique: true ,
required: true
},
members : [
{type: mongoose.Schema.Types.ObjectId,
ref: 'User' ,
default: []
} ]});
My question is : Is this the right way to do so , or should I maintain this club information at the User Collection only ? Maybe I need to optimize the query related to fetching all the Users belonging to a Club.
Upvotes: 0
Views: 87
Reputation: 18845
It's quite hard to say what's "the right way" to be honest, as this is most likely case by case depending on your application queries and architecture.
I have seen some people do as you designed above; Solving many-to-many relationships by using reference in both collection. This would work for your case queries above:
db.user.find({"clubs": ObjectId("000000")}); #Find all users belonging to certain club. db.club.find({"users": ObjectId("111111")}); # Find all clubs where a user belong to.
With two indexes on:
db.user.ensureIndex({"clubs": 1});
db.club.ensureIndex({"users": 1});
Though this may reduce the overall consistency. i.e. when you delete a club, you need to update the other affected documents as well. While in the process of the mentioned update, your documents may not be up-to-date. If you don't have mongodb on replicas, not accessing the db from distributed systems and you think this problem is not a big issue, then go for this design for the ease of query.
If you think the consistency mentioned above is a deal-breaker, then go with inserting only clubs reference in users collection. This is probably the most common design, and the one listed in mongodb official site.
I would suggest optimising your query first, before choosing to add complexities in your update/insert (Because you have to update all related docs by having ref in Users and Clubs).
Hope this helps.
Upvotes: 1