I am new to beanie, trying to model nested categories as a part of a FastAPI app, so I modeled the category collection as follows
class CategoryBase(Document):
name: Annotated[str, Indexed(unique=True)] = Field(max_length=100)
description: Optional[str] = Field(max_length=800, default=None)
options: Optional[list[str]] = Field(default_factory=list)
class CategoryIn(CategoryBase):
parent: Optional[PydanticObjectId] = Field(default=None)
children: Optional[list[PydanticObjectId]] = Field(default_factory=list)
class Category(CategoryIn):
parent: Optional[Link["Category"]] = Field(default=None)
children: Optional[list[BackLink["Category"]]] = Field(default_factory=list,
original_field="parent")
date_created: datetime = datetime.now(timezone.utc)
date_modified: datetime = datetime.now(timezone.utc)
class Settings:
name = "categories"
I built an end point that creates a “Category”. When I send a payload to it, a new document is created but I get the error in the title of the question.
The internal code that interact with the database looks as follows
class CategoryOps:
def __init__(self, _id: PydanticObjectId):
self.id = _id
async def get_category(self):
cat = await Category.get(self.id)
return cat
async def get_parent(self):
cat = await self.get_category()
parent = (await Category.get(cat.parent) if cat else None)
return parent
async def get_children(self):
cat = await self.get_category()
children = ( [await Category.get(child_id) for child_id in cat.children]
if self.category.children
else [] )
return children
class CategoryRepo:
async def create(cat: CategoryIn) -> Category:
parent, children = None, []
if cat.parent:
parent = await CategoryOps(cat.parent).get_category()
cat.parent = parent
if cat.children:
children = [await CategoryOps(c).get_category() for c in cat.children]
cat.children = children
new_category = Category(**cat.model_dump())
await new_category.save(link_rule=WriteRules.WRITE)
await new_category.sync()
return new_category
I expect when I pass a payload that includes a parent id, the children’s field in the parents object automatically gets populated with the link of the newly created category. The same if the payload includes children ids, I expect each of the children objects has its parent field populated with the id of the newly created category.