Search code examples
mongodbmeteorduplicatesunique

Got duplicate key error dup key: { : undefined }


I have an array field called udids in Meteor.users schema, which should contains unique elements. This is how I defined the index using SimpleSchema and Collection2:

new SimpleSchema({
  ...
  udids: {
    type: Array,
    index: true,
    unique: true,
    optional: true,
    sparse: true,
  },
  'udids.$': {
    type: String,
  },
  ...
})

However, when I start the app, I got this error: E11000 duplicate key error collection: meteor.users index: c2_udids dup key: { : undefined }.
I tried searching for the documents with udids = undefined in the database: db.users.find({ udids: { $type: 6 } }) ($type: 6 for undefined value) but it returns nothing.


Solution

  • The error message is a bit unclear so I had to guess the reason why. I found out that the current database already has some users with udids = []. I'm writing a migration script to unset this field from those users. Hopefully this will help others who have the same problem as me.