Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Limit Nesting Level of Linked Documents #834

Merged
merged 4 commits into from
Jan 25, 2024

Conversation

roman-right
Copy link
Member

@roman-right roman-right commented Jan 22, 2024

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 depth for all linked documents
  • depth for a specific linked document

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()

…it_link_recursion

# Conflicts:
#	tests/odm/conftest.py
#	tests/odm/models.py
max_ for settings params and no max_for find params
@roman-right roman-right merged commit 3258326 into main Jan 25, 2024
21 checks passed
@roman-right roman-right deleted the feature/limit_link_recursion branch January 25, 2024 04:59
@roman-right roman-right mentioned this pull request Jan 25, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

1 participant