使用 MongoEngine 'unique_with' 时出现索引错误:索引已存在且具有不同的选项

问题描述

我正在使用 MongoEngine 并且我已经声明了两个相关的类:

from mongoengine import StringField,DynamicDocument,BooleanField


class BaseFile(DynamicDocument):
    name = StringField(unique_with=["category"])
    category = StringField()
    active = BooleanField()

    Meta = {
        "indexes": [
            "active"
        ],"allow_inheritance": True,}


class SpecialFile(BaseFile):
    tag = StringField()

查询其中一个类时出现以下错误

OperationFailure: Index with name: name_1_category_1 already exists with different options

但是,我之前没有创建过那个索引,它只声明了一次(在 unique_with 中)。如何避免这个错误

解决方法

这是一个带有 mongoengine 的 known open issue:当结合使用 unique_with 和继承时,你会得到那些索引错误。 Mongoengine 尝试创建索引两次,错误发生。

但是有一个解决方法(显示在链接的 github 问题中):在 meta 字典中声明唯一性,使用索引声明。

from mongoengine import StringField,DynamicDocument,BooleanField


class BaseFile(DynamicDocument):
    name = StringField(required=True)
    category = StringField(required=True)
    active = BooleanField()

    meta = {
        "indexes": [
            "active",{"fields": ["name","category"],"unique": True},],"allow_inheritance": True,}


class SpecialFile(BaseFile):
    tag = StringField()

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...