BeanieODM / beanie

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

Linked Documents Nested Inside Embedded Models Aren't Saved to Their Own Collections #724

Closed mhdzumair closed 9 months ago

mhdzumair commented 1 year ago

Describe the bug When using the Linkfield inside nested BaseModels and trying to insert the parent Document, Beanie does not save the linked document in its own separate collection as expected. Instead, it treats the linked document as an embedded document inside the parent Document, saving it directly within the parent document's collection.

To Reproduce

import asyncio
import motor.motor_asyncio
from beanie import init_beanie, Document, Link, WriteRules
from pydantic import BaseModel

DATABASE_URL = "mongodb://localhost:27017"
DATABASE_NAME = "test_beanie_db"
client = motor.motor_asyncio.AsyncIOMotorClient(DATABASE_URL)
database = client[DATABASE_NAME]

class Streams(Document):
    torrent_name: str
    filename: str
    class Settings:
        collection = "streams"

class Episode(BaseModel):
    episode_number: int
    streams: list[Link[Streams]]

class Season(BaseModel):
    season_number: int
    episodes: list[Episode]

class Series(Document):
    title: str
    seasons: list[Season]
    class Settings:
        collection = "series"

async def run():
    await init_beanie(
        database=database,
        document_models=[Streams, Series],
    )
    # Inserting a series
    stream = Streams(torrent_name="sample_torrent", filename="sample_file.mkv")
    episode = Episode(episode_number=1, streams=[stream])
    season = Season(season_number=1, episodes=[episode])
    series = Series(title="Sample Series", seasons=[season])
    await series.insert(link_rule=WriteRules.WRITE)
    # Check collections
    streams_in_db = await Streams.find_all().to_list()
    series_in_db = await Series.get(series.id)
    print(streams_in_db)
    print(series_in_db)

asyncio.run(run())

Expected behavior The Streams document should be stored in its own streams collection. The Series document should only have a reference/link to the Streams document.

Current behavior The Streams data is embedded within the Series collection instead of being referenced from its own streams collection.

Additional context This issue arises particularly when using nested BaseModel structures and trying to store linked documents from within these nested structures.

roman-right commented 1 year ago

Hi! Thank you for the catch. I'll check and fix it this/next week.

roman-right commented 10 months ago

Hi @mhdzumair , Sorry for late response. Beanie support only top-level links currently.

github-actions[bot] commented 9 months ago

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

mhdzumair commented 9 months ago

You can close this story.