BeanieODM / beanie

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

Limit Nesting Level of Linked Documents #834

Closed roman-right closed 5 months ago

roman-right commented 5 months ago

Define a document

It is possible to define nested linked documents with Beanie. Sometimes this can lead to infinite recursion. To prevent this, or to decrease the database load, you can limit the nesting depth. By default, it is set to 3, which means it will fetch up to 3 levels of nested documents. You can configure:

Maximum:

class Sample(Document):
    num: int
    category: Link[Category]

    class Settings:
        max_nesting_depth = 2  # Maximum nesting depth for all linked documents of this model

Specific:

class Sample(Document):
    num: int
    category: Link[Category]

    class Settings:
        max_nesting_depths_per_field = {
            "category": 1  # Nesting depth for a specific field
        }

Find

You also can limit the nesting depth during find operations.

from beanie import Document, Link
from typing import Optional

class SelfLinkedSample(Document):
    name: str
    left: Optional[Link["SelfLinkedSample"]]
    right: Optional[Link["SelfLinkedSample"]]

You can set up maximum depth for all linked documents:


await SelfLinkedSample.find(
    SelfLinkedSample.name == "test",
    fetch_links=True,
    nesting_depth=2
).to_list()

Or you can set up depth for a specific field:

await SelfLinkedSample.find(
    SelfLinkedSample.name == "test",
    fetch_links=True,
    nesting_depths_per_field={
        "left": 1,
        "right": 2
    }
).to_list()