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?