beanie icon indicating copy to clipboard operation
beanie copied to clipboard

Renaming id field to _id

Open fedirz opened this issue 2 years ago • 4 comments

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)

fedirz avatar Mar 28 '22 06:03 fedirz

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.

roman-right avatar Mar 28 '22 13:03 roman-right

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')

fedirz avatar Mar 28 '22 21:03 fedirz

For now this is impossible, but I think this makes sense. I'll add this to my TODO list

roman-right avatar Apr 27 '22 11:04 roman-right

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

jziolkowski avatar May 10 '22 19:05 jziolkowski

This issue is stale because it has been open 30 days with no activity.

github-actions[bot] avatar Feb 08 '23 02:02 github-actions[bot]

This issue was closed because it has been stalled for 14 days with no activity.

github-actions[bot] avatar Feb 22 '23 02:02 github-actions[bot]