sonlexqt
sonlexqt

Reputation: 6469

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.

Upvotes: 2

Views: 1624

Answers (2)

sonlexqt
sonlexqt

Reputation: 6469

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.

Upvotes: 2

blueren
blueren

Reputation: 2870

I've not tested this, but it should ideally work.

  1. Used Meteor.users as a collection name. You may want to replace it with whichever collection you want to run the validation against.
  2. Made use of custom function to find at least one doc which contains the field's value in udids.
  3. If you don't have access to the collection on the client side, then you can edit the custom function and have it handled asynchronously.

new SimpleSchema({
            ...
            'udids': {
                optional: true,
                type: [String], // an array of string eg. ['A','B']
                custom: function() {

                    // this.value = current field's value
                    // Below mongo query will check to see if there is at least one 
                    // mongo doc whose udids contains the currently entered field's value.
                    // if found, then return the error message.

                    if (Meteor.users.findOne({
                            udids: {
                                $in: [this.value]
                            }
                        })) {
                        return "duplicateMsg";
                    }
                },
                ...
     });

SimpleSchema.messages({ duplicateMsg:"Udid already exists"});

Upvotes: 0

Related Questions