Ying Yangz
Ying Yangz

Reputation: 177

Many to Many Data modelling in mongodb

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?

Upvotes: 0

Views: 1204

Answers (2)

gnerkus
gnerkus

Reputation: 12019

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' }]
});

Upvotes: 1

alex10
alex10

Reputation: 2756

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 ] }})

Upvotes: 0

Related Questions