Hey @Arie_Levental,
Welcome to the MongoDB Community!
Based on the schema, it seems there is a “User collection” that contains “User” documents (students).
The “Institution collection” contains “Institution” documents, with each document having an array of student ObjectIds in the student’s field as a reference.
So, to better understand the issue you are facing - Is the same student ObjectId being added multiple times to the students array in an Institution document?
For example:
// Institution document
{
_id: 1,
name: "University of MongoDB",
students: [
ObjectId("601af221b06858b7b8e35672"), // John's student ID
ObjectId("601af221b06858b7b8e35672") // John's student ID added again
]
}
To prevent this, you can check if it already exists before adding or using $addToSet operator to only add unique values.
The unique:true on the students field does not help here, since that only ensures the field value itself is unique per document, not the array elements.
I hope it clarifies your doubts. In case of any further questions feel free to reach out!
Regards,
Kushagra