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