NotUniqueError: Tried to save duplicate unique keys

Question:

I keep getting the above mentioned error. I have deleted the existing db field id which was set to unique. But on save I got the below exception

raise NotUniqueError(message % unicode(err))
NotUniqueError: Tried to save duplicate unique keys (E11000 duplicate key error index: test.users.$id_1  dup key: { : null })

My user table looks like,

class Users(db.Document, UserMixin):
    name = db.StringField(max_length=50)
    email = db.StringField(max_length=255)
    password = db.StringField(max_length=255)
    city = db.StringField(max_length=125)
    active = db.BooleanField(default=True)
    company =  db.StringField(max_length=255)
    type = db.StringField(max_length=15)
    confirmed_at = db.DateTimeField()
    role = db.ReferenceField(Role)

    meta = {'strict': False}

I also tried unsetting the id attribute using,

cls.objects.update(**{"unset__id": 1})

But it throws this exception,

raise OperationError(u'Update failed (%s)' % unicode(err))
OperationError: Update failed (Mod on _id not allowed)

I just want to save the user model without id field.

Asked By: Avinash Raj

||

Answers:

If call list_indexes() it will show an unique index on the id field.

You need to drop the unique index on the id field in the collection as well using db.collection.dropIndex().

I am not sure if mongoengine provides a drop_index class method but you can do this from the shell.

Answered By: styvane

Quick Answer

You can use db.collectionName.dropIndexes() to drop all the indexes got created on the database level except the _id index. Also you can manually drop the indexes using db.collectionName.dropIndex()

My Question

I have got a similar issue after passing unique_with constraint on some fields and even after removing the unique_with constraint from the field & passing unique=False things didn’t changed then I looked into database from shell using command db.collectionName.getIndexes() and found that their were indexes created at database level and I was so intrigued knowing this as MongoEngine creates the Schema only at Application level then why did that happened.

Answered By: Akshat Jain