beanie icon indicating copy to clipboard operation
beanie copied to clipboard

[BUG] Beanie should have a way to handle an `id` field different than underlying `_id`

Open nahuel opened this issue 11 months ago • 5 comments

Seems like defining id on the beanie.Document base class is a miss-design, as it's very frequent that your domain model has an id field (business related, a very common field name) distinct from the underlying Mongo _id field.

For example:

import pydantic
import beanie

# Pure pydantic model, e.g. maybe generated from OpenAPI specs, used everywhere:
class User(pydantic.BaseModel):
    id : str
    name : str 
    # ...

# Now we want to store it as such on Mongo
class UserDB(beanie.Document, User)
   class Settings:
        collection_name = "users"

Pylance detects the bad override Base classes for class "UserDB" define variable "id" in incompatible way

This also happens when you must create Beanie models from existing Mongo collections that use a business related id field. In that case you cannot use Beanie.

As Pydantic doesn't support fields starting with _, maybe _id can be aliased to something more specific and less prone to collision, like mongoDocumentId and still be mapped to the underlying _id.

nahuel avatar Jan 21 '25 14:01 nahuel

I know that in my particular use case I want to pretend _id just doesn't exist. I like that id is just a mapping to the underlying _id but that itself isn't well handled since in the OpenAPI schema it still shows as _id if I decide to expose the db model directly as the return API return type.

I feel like there is there is a bunch related to _id vs id that is odd with Beanie and needs to be fixed.

I think most people are in the same boat as me and just want to pretend _id doesn't exist, and use id, and that should be the default, and the schema should return as id not _id.

But for uses cases like yours, where you want _id AND id as distinct fields, that should be allowed, with you able to alias _id to another field.

unexceptable avatar Jan 29 '25 02:01 unexceptable

Bumping for visibility.

I’ve run into this bug as well.

trojanEcstasy avatar Feb 07 '25 22:02 trojanEcstasy

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

github-actions[bot] avatar Mar 10 '25 02:03 github-actions[bot]

Bumping for visibility. similar problem with prisma, it is a crazy world. :P

ice6 avatar Mar 25 '25 07:03 ice6

You can do:

from beanie import Document
from pydantic import Field

class User(Document):
    user_id: int = Field(alias="id")  # This field in the database is "id"

ghmahdi21 avatar Apr 15 '25 23:04 ghmahdi21