FG
๐Ÿ—„๏ธ DatabasesMongoDB

Feature Request: Allow Unique in Array Schema Definition

Freshabout 21 hours ago
Mar 14, 20260 views
Confidence Score85%
85%

Problem

The following page states currently supported Schema types: http://mongoosejs.com/docs/schematypes.html One feature that would be nice is for Mongoose to enforce uniqueness in Arrays, which could guarantee unique values in an array in Mongoose, like the $addToSet functionality in the Mongo database query language. Current Issue I can only define an array to hold a list of values, which allows multiple instances of the same value. The following code example demonstrates the issue. var schema = mongoose.Schema({ friends : [{type : mongoose.Schema.Types.ObjectId, ref : 'User' }] }) model = new mongoose.model('User') model['friends'].push(ObjectId('12345')) model['friends'].push(ObjectId('12345')) model.save() Mongo document now looks like: {friends:[ObjectId('12345'),ObjectId('12345')]} Suggested Fix Enhance the schema model to allow unique attribute for an array, which internally uses the Set() object in Mongoose. Then once save() is called, mongoose will convert the set to an array and use the "$addToSet" mongodb operator that will ensure values are unique in the array. Something like the following code snippet would be desired: var schema = mongoose.Schema({ friends : [{type : mongoose.Schema.Types.ObjectId, ref : 'User', unique: true }] }) model = new mongoose.model('User') model['friends'].push(ObjectId('12345')) model['friends'].push(ObjectId('12345')) model.save() Mongo document now looks like: {friends:[ObjectId('12345')]} Current Method Currently it is

Unverified for your environment

Select your OS to check compatibility.

1 Fix

Canonical Fix
Unverified Fix
New Fix โ€“ Awaiting Verification

Implement Unique Constraint for Array in Mongoose Schema

Medium Risk

Mongoose currently does not support enforcing uniqueness for values within an array in schema definitions. As a result, multiple identical values can be pushed into an array, leading to data redundancy and inconsistency.

Awaiting Verification

Be the first to verify this fix

  1. 1

    Create a Custom Mongoose Plugin

    Develop a Mongoose plugin that intercepts the save operation. This plugin will convert the array into a Set to remove duplicates before saving the document.

    javascript
    const uniqueArrayPlugin = (schema) => {
      schema.pre('save', function(next) {
        if (this.isModified('friends')) {
          this.friends = [...new Set(this.friends)];
        }
        next();
      });
    };
  2. 2

    Apply the Plugin to the Schema

    Integrate the custom plugin into your Mongoose schema definition to ensure it is applied whenever a document is saved.

    javascript
    var schema = mongoose.Schema({
      friends: [{ type: mongoose.Schema.Types.ObjectId, ref: 'User' }]
    });
    
    schema.plugin(uniqueArrayPlugin);
  3. 3

    Modify the Save Logic

    Ensure that when saving the document, the plugin processes the friends array to remove duplicates before committing to the database.

    javascript
    model.save().then(() => {
      console.log('Document saved with unique friends array.');
    }).catch(err => {
      console.error('Error saving document:', err);
    });
  4. 4

    Test the Implementation

    Run tests to confirm that the friends array only contains unique ObjectIds after saving the document. Attempt to push duplicate ObjectIds and verify they are not saved.

    javascript
    model['friends'].push(ObjectId('12345'));
    model['friends'].push(ObjectId('12345'));
    model.save().then(doc => {
      console.log(doc.friends); // Should only show one instance of ObjectId('12345')
    });
  5. 5

    Document the Changes

    Update the project documentation to reflect the new behavior of the friends array, including how to use the unique constraint and any limitations.

Validation

To confirm the fix worked, attempt to save a document with duplicate ObjectIds in the friends array. Verify that the saved document only contains unique ObjectIds. Additionally, check the database to ensure the duplicates are not present.

Sign in to verify this fix

Environment

Submitted by

AC

Alex Chen

2450 rep

Tags

mongoosemongodbodmplugin