BeanieODM / beanie

Asynchronous Python ODM for MongoDB
http://beanie-odm.dev/
Apache License 2.0
1.99k stars 211 forks source link

[BUG] Can not create dbref without id #731

Closed ID2343242 closed 9 months ago

ID2343242 commented 11 months ago

Describe the bug Trying on the Link demos but getting exception. Can not create dbref without id

To Reproduce

class Door(Document):

class Settings:
    name = "door"

height: int = 2
width: int = 1

class Window(Document):

class Settings:
    name = "window"

x: int = 10
y: int = 10

class House(Document):

class Settings:
    name = "house"

name: str
door: Link[Door]
windows: List[Link[Window]]

document_models = [ House, Door, Window ] await init_beanie(database=db, document_models=document_models)

door = Door() window = Window() house = House(name="MyHouse", door=door, windows=[window])

await house.save()

Expected behavior

Save a House document with a Window and Door document in separate tables.

Additional context

Exception has occurred: DocumentWasNotSaved Can not create dbref without id File "/test.py", line 74, in main await house.save() File "/test.py", line 76, in asyncio.run(main()) beanie.exceptions.DocumentWasNotSaved: Can not create dbref without id

ID2343242 commented 11 months ago

I have put in a few bugs but I've now removed Beanie from my project now so please prioritise other peoples bugs.

mike-pisman commented 10 months ago

You need to use link_rule=WriteRules.WRITE when saving the document, example provided. More info at https://beanie-odm.dev/tutorial/relations/#write


class Window(Document):
    x: int = 10
    y: int = 10

class Door(Document):
    height: int = 2
    width: int = 1

class House(Document):
    name: str
    door: Link[Door]
    windows: list[Link[Window]]

async def example():
    client = AsyncIOMotorClient("mongodb://***@***:27017")

    await init_beanie(database=client.test,
                      document_models=[House, Door, Window])

    door = Door()
    window = Window()
    house = House(name="MyHouse", door=door, windows=[window])

    await house.save(link_rule=WriteRules.WRITE)

if __name__ == "__main__":
    asyncio.run(example())
github-actions[bot] commented 9 months ago

This issue is stale because it has been open 30 days with no activity.

github-actions[bot] commented 9 months ago

This issue was closed because it has been stalled for 14 days with no activity.