I've modeled a has-many relationship in MongoDB with a Group that has an array of Students as one of the fields.
When a Student is deleted, I want to go through all the Groups, and for each Group that has the deleted_student in its Group.Students, remove the deleted_student from the array.
To remove the deleted_student from the array, I have a helper function, RemoveItem that I'd liek to use.
What's the "Mongo" way of apply this function to all the records in a collection? Or should I just return all the Groups, then iterate through each and perform the operation on the field. Something like this (in Go using the mgo library)
groups := conn.C("groups")
allGroups := groups.Find()
for _, group := range allGroups {
group.Students = RemoveItem(id, group.Students)
}
// Helper function that removes a mgo.DBRef from an array of mgo.DBRefs based on ID string
func RemoveItem(objectId string, array []mgo.DBRef) []mgo.DBRef {
updatedArray := []mgo.DBRef{}
for _, item := range array {
if item.Id != objectId {
updatedArray = append(updatedArray, item)
}
}
return updatedArray
}