NotUniqueError:尝试保存重复的唯一键 [英] NotUniqueError: Tried to save duplicate unique keys

查看:502
本文介绍了NotUniqueError:尝试保存重复的唯一键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不断收到上述错误.我已经删除了设置为唯一的现有数据库字段id.但是保存下来,我得到了下面的异常

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 })

我的user表看起来像

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}

我还尝试使用

取消设置id属性

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)

我只想保存没有id字段的用户模型.

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

推荐答案

如果调用

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().

我不确定mongoengine是否提供drop_index类方法,但是您可以从shell中执行此操作.

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

这篇关于NotUniqueError:尝试保存重复的唯一键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆