How to avoid duplicated values?

I’m a new developer and started my journey working with MongoDB.
I have this mongoose scheme and for some reason I still manage to have duplicated items in the students array (student is another User scheme):

import mongoose from "mongoose";

const institutionSchema = mongoose.Schema(
    name: {
      type: String,
      required: true,
      min: 2,
      max: 50,
    students: [
        type: mongoose.Schema.Types.ObjectId,
        ref: "User",
        unique: true,
        sparse: true,
    logoPath: {
      type: String,
      default: "",
  { timestamps: true }

const Institution = mongoose.model("Institution", institutionSchema);

export default Institution;

How can I fix this?
What are those validators for?

Thanks :innocent:

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!