How to enforce uniqueness for the sequence field in a nested MongoDB schema using Mongoose?

I’m working on a project where I have three Mongoose schemas: Article, Module, and Course. The Module schema has an array of articles, and the Course schema has an array of modules, each with a sequence field to determine the order. I want to ensure that the sequence field is unique within its respective array. However, I’m having trouble enforcing uniqueness for the sequence field. This given code doesn’t work for this use case.

const articleSchema = new Schema({
    // ... (article schema fields)
});

const moduleSchema = new Schema({
    // ... (module schema fields)
    articles: [{
        article: {
            type: Schema.Types.ObjectId,
            ref: 'Article',
        },
        sequence: {
            type: Number,
            required: true,
            unique: true, // This doesn't seem to be working
        }
    }],
});

const courseSchema = new Schema({
    // ... (course schema fields)
    modules: [{
        module: {
            type: Schema.Types.ObjectId,
            ref: 'Module',
        },
        sequence: {
            type: Number,
            required: true,
            unique: true, // This also doesn't seem to be working
        },
    }],
    // ... (more course schema fields)
});


const Article = mongoose.model('Article', articleSchema);
const Module = model('Module', moduleSchema);
const Course = model('Course', courseSchema);

Hey @Prateek_Kumar2,

Welcome to the MongoDB Community :sparkles:

The unique option in Mongoose is used to ensure that the specified field has a unique value across all documents in the collection. However, in your case, you want to enforce uniqueness within an array of subdocuments.

Mongoose does not directly support unique indexes at the subdocument level. To achieve uniqueness within an array of subdocuments, you can use a combination of custom validation and the validate option. Alternatively, you can refer to this npm package - mongoose-unique-array and see if it helps resolve your issue.

Additionally, you can utilize the $addToSet operator to add a value to an array only if the value is not already present.

Regards,
Kushagra