代码之家  ›  专栏  ›  技术社区  ›  Jundiaius

使用MongoEngine'unique_with'时发生索引错误:索引已存在,但具有不同的选项

  •  0
  • Jundiaius  · 技术社区  · 4 年前

    我正在使用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 ). 如何避免这种错误?

    1 回复  |  直到 4 年前
        1
  •  0
  •   Jundiaius    4 年前

    这是一个 known open issue 使用mongoengine:使用时会出现这些索引错误 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()