问题描述
我正在使用 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()