Mongoose unique index on subdocument Mongoose unique index on subdocument mongoose mongoose

Mongoose unique index on subdocument


Long story short: Mongo doesn't support unique indexes for subdocuments, although it allows creating them...


This comes up in google so I thought I'd add an alternative to using an index to achieve unique key constraint like functionality in subdocuments, hope that's OK.

I'm not terribly familiar with Mongoose so it's just a mongo console update:

var foo = { _id: 'some value' }; //Your new subdoc heredb.yourCollection.update({ '_id': 'your query here', 'myArray._id': { '$ne': foo._id } },{ '$push': { myArray: { foo } })

With documents looking like:

{  _id: '...',  myArray: [{_id:'your schema here'}, {...}, ...]}

The key being that you ensure update will not return a document to update (i.e. the find part) if your subdocument key already exists.


First objectId length in mongodb must be 24. Then you can turn off _id, and rename _id as id or others,and try $addToSet. Good luck.

CoffeeScript example:

FromSchema = new Schema(  source: { type: String, trim: true }  version: String  { _id: false }//to trun off _id)VisitorSchema = new Schema(  id: { type: String, unique: true, trim: true }  uids: [ { type: Number, unique: true} ]  from: [ FromSchema ])//to updateVisitor.findOneAndUpdate(  { id: idfa }  { $addToSet: { uids: uid, from: { source: source, version: version } } }  { upsert: true }  (err, visitor) ->    //do stuff