从 mongo 引擎中的另一个嵌入文档访问嵌入文档

Access to an embedded document from another embedded document in mongo engine

我在 mongo 引擎中有一个文档,其中有一个嵌入式文档。这是我的模型:

class Problem(EmbeddedDocument):
    id = ObjectId()

class Result(EmbeddedDocument):
    problem = ReferenceField('Problem')

class Contest(Document):
    problem = EmbeddedDocumentField(Problem)

现在我想从 Result 模型访问 Problem。我该怎么做?

EmbeddedDocumentDocument的根本区别在于EmbeddedDocument只存在于Document中。

EmbeddedDocument is a Document that isn’t stored in its own collection. EmbeddedDocuments should be used as fields on Documents through the EmbeddedDocumentField field type.

因此EmbeddedDocument不能有主键,EmbeddedDocument它只是文档中的一个dict。详见documentation

id = ObjectId() 这不是字段声明。所有可能的字段都已列出 there。由于声明主键字段,您需要在字段参数中使用 primary_key=True

problem = ReferenceField('Problem') EmbeddedDocument 不能作为引用,因为它不是字段。因此,声明嵌入字段的正确方法如下所示:problem = EmbeddedDocumentField(Problem)