1

I have Users and Groups as schemas, and both schemas have references to the other: When a user gets added or removed from a group, they need to be added or removed from that group, and their list of groups need to be updated. Is this the best way to do this:

  • Given a new list of groups that the user belongs to (from the form where group assignment happens) replace the old list of groups under the user with the new list;
  • Query database for all groups that list this user as member. For each group in the result, if the group is in the new list of user's groups, do nothing. If the group is not in that list, remove the user from that group list.
  • Get any groups that were not found in the query above and add the user to them.

For reference, here are the models:

var GroupSchema = new Schema({
  'name' : {
    type: String,
    unique: true,
    required: true
  },
  'users' : [{
    type: Schema.Types.ObjectId,
    ref: 'User'
  }]
});

var UserSchema = new Schema({
  'email' : {
    type : String,
    isEmail : true,
    required : true,
    unique: true,
    index: true
  },
    'displayName' : {
    type : String,
    required : true
  },
    'admin' : {
    type: Boolean,
    default : false,
    index: true
  },
    'invitedBy' : {
    type: Schema.Types.ObjectId,
    ref: 'User'
  },
    'groups' : [{
    type: Schema.Types.ObjectId,
    ref: 'Group'
  }]
});
Mikey
  • 6,728
  • 4
  • 22
  • 45
Tom Hughes
  • 576
  • 6
  • 8
  • 1
    You should read this [answer](http://stackoverflow.com/a/25103393/1022914). Option 3, such as what you are currently doing, seems like it would be great for querying but you would have to do a lot of work to make sure everything is consistent when inserting/updating/deleting. I usually do option 1 or 2. – Mikey May 10 '17 at 00:16
  • Thanks, went with option 2 - creating a static getGroupsByUser function on the User model to get list of users belonging to a group or groups was pretty simple: this.find().where('groups').in(groupIds).exec() and obviated need to keep updating info in both places. – Tom Hughes May 12 '17 at 08:46
  • For anyone else that stumbles on this question, this may be helpful if you still want to go with option 3: http://stackoverflow.com/questions/20009122/removing-many-to-many-reference-in-mongoose – Tom Hughes May 12 '17 at 08:55

0 Answers0