BeanieODM / beanie

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

[BUG] Can not create dbref without id #731

Closed ID2343242 closed 11 months ago

ID2343242 commented 1 year 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 1 year 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 1 year 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 1 year ago

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

github-actions[bot] commented 11 months ago

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