Search code examples
mongodbdocument-databasedatabase

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?


Solution

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