Skip to content

Feature Request: Allow Unique in Array Schema Definition #3347

Closed
@ccravens

Description

@ccravens

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 being suggested to create a seperate update() function with the "$addToSet" parameter, which seems to be more work and burden on the developer than it should be. Please refer to the following:

https://groups.google.com/forum/#!topic/mongoose-orm/QSpr_7rtEYY
http://stackoverflow.com/questions/15921700/mongoose-unique-values-in-nested-array-of-objects

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions