What is the best way of modelling such a relationship? I have a room collection and a user collection. A room can contain many users. A user can belong to many rooms. I was thinking of inserting users of a room in an array (?) in the room collection. Is there a better way or is it incorrect altogether to do it the way I am doing it?
Asked
Active
Viewed 1,200 times
0
-
this is a typical case where SQL would be a better tool than NoSQL – Eric Jan 19 '16 at 20:43
2 Answers
1
Your approach is correct. MongoDB does not require a schema so you can store references to items from another collection in an item of one collection.
You can store an array of the ObjectIds from the room
collection in the user
collection to identify which rooms a person has joined. Likewise, you can store an array of the ObjectIds from the user
collection in the room
collection to identify what users have joined a room.
Your schemas would look similar to these:
var UserSchema = new Schema({
'name': String,
rooms: [{ type: Schema.Types.ObjectId, ref: 'RoomSchema' }]
});
var RoomSchema = new Schema({
'name': String,
'users': [{ type: Schema.Types.ObjectId, ref: 'UserSchema' }]
});

gnerkus
- 11,357
- 6
- 47
- 71
-
Thanks for the reply. Will this be a problem if the there are no limits on the number users that can join a specific room? For example if there are 200 users in a room, will that cause significant increase in document size? – Ying Yangz Jan 19 '16 at 20:55
-
It won't because you're only storing the IDs of the users and not the user data. – gnerkus Jan 19 '16 at 21:02
0
It might look like:
{_id:"123", "type":"room", "users":[ 111, 222]}
{_id:"111", "type":"user", "room": [ 123, 456]}
Example add user in room:
db.test.update( { _id: "123" }, { $addToSet: {"users": 333 } } )
Example delete user from room:
db.test.update( { _id: "123" }, { $pullAll: { scores: [ 111, 222 ] }})

alex10
- 2,726
- 3
- 22
- 35