Closed tkaraouzene closed 6 months ago
After a small investigation, it seems the issue occurs here
Indeed, if I run in debug mode I can see that
self.id
Out[2]: UUID('68d76e1a-65d3-4d39-be25-b8fd241edd4c')
When
result.inserted_id
Out[3]: ObjectId('654e26d163172aba437b7f72')
So it seems the provided id is not considered at document insertion.
If I modify my document as follow:
class MyDocument(Document):
id: UUID = Field(alias="_id", default_factory=uuid4)
name: str
All works! It is a good workaround but whatever it is not the expected behavior moreover it was working properly with pydantic v1
To also add on to @tkaraouzene 's comment, I have this issue when saving my documents as a Link Write / Object.
Although documents (only link documents, i.e. child documents, parent document does not save at all) with UUID still saves into database (objectId now in UUID format), however python still flags out this error:
ValueError: cannot encode native uuid.UUID with UuidRepresentation.UNSPECIFIED. UUIDs can be manually converted to bson.Binary instances using bson.Binary.from_uuid() or a different UuidRepresentation can be configured. See the documentation for UuidRepresentation for more information.
To Reproduce:
from beanie import Document, Link, WriteRules
class Content(Document):
id: UUID = Field(default_factory=uuid4) # error here (1)
publisher = str
category = str
class Book(Document):
id: UUID = Field(default_factory=uuid4) # error here (1)
book_pub: int
book_content: Link[Content] | None
async def create_example_book() -> None:
new_content = Content(
publisher = "publisher_zebra",
category = "science_fiction"
)
new_book_data = Book(
book_pub=12345,
book_content=new_content,
)
await new_book_data.save(link_rule=WriteRules.WRITE) # error here (1)
error (1) : Failed to start mongodb. ValueError: cannot encode native uuid.UUID with UuidRepresentation.UNSPECIFIED. UUIDs can be manually converted to bson.Binary instances using bson.Binary.from_uuid() or a different UuidRepresentation can be configured. See the documentation for UuidRepresentation for more information.
In order to solve this issue, I think it's necessary to precise the uuidRepresentation in your AsyncIOMotorClient :
Exemple with FastAPI
app.db = AsyncIOMotorClient([...], uuidRepresentation='standard').your_db
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.
Hi everyone!
Describe the bug Beanie cannot insert document when
id
Field
is an UUIDAdditional context
pydantic
: 2.4.2beanie
: 1.23.3python
: 3.9.13To Reproduce
It raises following error:
It seems the error comes from
parse_object_as
cannot convertnew_id
fromPydanticObjectId
toUUID
but it should be possible according to the documentation: https://beanie-odm.dev/tutorial/defining-a-document/#idFor information, running following lines works, however I really prefer keep UUID instead of PydanticObjectId: