Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add objects/links to a set of links in beanie?

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?

like image 325
Ambitions Avatar asked Oct 23 '25 03:10

Ambitions


1 Answers

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.

like image 164
Pokemon Avatar answered Oct 25 '25 17:10

Pokemon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!