4

Assume that I have these Beanie Documents which are based, by the way, on Pydantic Models:

File name: models.py

from beanie import Document, Link

class A(Document):
    first: int
    second: str

class B(Document):
    third: float
    a_links: set[Link[A]] = {}

and I have this FastAPI route:

File name: main.py

from fastapi import FastAPI, HTTPException, status

from beanie import PydanticObjectId, Link

from .models import A, B

app = FastAPI()

@app.post('/b/{b_object_id}/add-link/{a_object_id}')
async def add_link(b_object_id: PydanticObjectId, a_object_id: PydanticObjectId):
    b = await B.get(b_object_id)
    if not b:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND)
    a = await A.get(a_object_id)
    if not a:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND)
    b.a_links.add(Link(a))
    await b.save()
    return b

I am talking about this line of code:

b.a_links.add(Link(a))

If I wrote it as it is, I will get this error: Parameter 'document_class' unfilled

Also, if I wrote it as:

b.a_links.add(Link(a, document_class=A))

I will get this error: Expected type 'DBRef', got 'A' instead

Finally, if I wrote it as:

b.a_links.add(Link(ref=a.id, document_class=A))

I will get this error: Expected type 'DBRef', got 'PydanticObjectId | None' instead

How to add it in a correct way?

1 Answer 1

2

The correct line of code is b.a_links.add(a)

The issue comes from trying to manually create the Link object. Beanie is designed to handle this for you automatically. You should add the document object itself to the set. Beanie will convert it into a DBRef link when you save the document.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.