在 Mongoengine 中添加文档并更新另一个文档中的引用字段

问题描述 投票:0回答:1

我有两个文档,我想使用 _ID 通过参考字段链接在一起。这个想法是创建文档,将它们保存到数据库中,获取 _ID 信息并将其附加到另一个文档的参考列表中。由于文件将在不同时间创建,我无法事先建立两者。

这是迄今为止的代码以及发生的错误。

from mongoengine import StringField, Document, DateField, ReferenceField

class GameWrapper(Document)
     title: StringField()
     year: DateField()

class GameCompanyWrapper(Document):
     Company_Name: StringField()
     published_games: ReferenceField(GameWrapper)

class IstrumentService:
    mongo_url: str = None 

    def save(self, inst: GameWrapper) -> ObjectId:
        saved_inst: inst = inst.save()
        return saved_inst.id

instrument_service = IstrumentService()

GCW = GameCompanyWrapper()
GCW.Company_Name = "Squaresoft"
IstrumentService.save(GCW)

GW = GameWrapper()
GW.Title = "Final Fantasy"
ob_ID = IstrumentService.save(GCW)

GCW.published_games = ob_ID
IstrumentService.save(GW)

AttributeError:“ObjectId”对象没有属性“_data”

我假设 objectID 是对数据库中条目的引用,那么为什么它会抛出 no attribute '_data' 错误?

python mongoengine
1个回答
0
投票

在将其分配给 GCW 之前,您必须保存

GW
。在你的代码中:

GW = GameWrapper()
GW.Title = "Final Fantasy"
ob_ID = IstrumentService.save(GCW)

GW
创建了对象GW,但它没有保存到数据库,因此它没有对象Id。现在,您的
ob_ID
是 GCW,之后您将此 Id 分配给 GCW.published_games 并保存
GW
。这陷入了 GW 和 GCW 之间。

我重写了你的代码,并且成功了。在分配给 GCW 之前保存 GW

    instrument_service = IstrumentService()
    GCW = GameCompanyWrapper()
    GCW.Company_Name = "Squaresoft"
    instrument_service.save(GCW)

    GW = GameWrapper()
    GW.title = "Final Fantasy"
    ob_ID = instrument_service.save(GW)

    GCW.published_games = ob_ID
    instrument_service.save(GCW)
© www.soinside.com 2019 - 2024. All rights reserved.