beanie
beanie copied to clipboard
Renaming id field to _id
Is there a way to change the default behaviour so that MongoDb's _id field gets mapped to _id field of the Document instead of id?
class Product(Document):
_id: PydanticObjectId
id: int
product = Product(id=1)
await product.insert()
I want that code to produce Product(_id=ObjectId("6241549bd405d14b4328244d"), id=1)
instead of just Product(id=1)
Hey. This is a pydantic limitation. Fields, starting with an underscore are private attributes in the pydantic models. Id in Beanie is mapped to _id
in MongoDB, using an alias.
Do you think it would be possible to give the user a choice to decide what model field _id
gets mapped to? For example, my data already has an id field and it would be nice if I could use it instead of having to rename it.
Maybe something like this:
class Product(Document):
id: int
class Config:
fields = {"object_id": "_id"}
product = Product(id=5)
await product.insert()
print(product.id)
### 5
print(product.object_id)
### ObjectId('6242291dd539926bcf5449c0')
For now this is impossible, but I think this makes sense. I'll add this to my TODO list
Why not use the field alias that is implemented in pydantic for this exact purpose?
id: Optional[PyObjectId] = Field(alias='_id')
I would love this feature implemented. I just started using beanie with fastapi and I'm slightly annoyed that the field name is _id in the openapi schemas
This issue is stale because it has been open 30 days with no activity.
This issue was closed because it has been stalled for 14 days with no activity.