Pydantic v2 and ObjectID fields

Hello MongoDB community!

Pydantic v2 was recently released.

I found this document (Getting Started with MongoDB and FastAPI | MongoDB) in the MongoDB quickstarts about using FastAPI, MongoDB and Pydantic, but as Pydantic v2 has several API changes and deprecations, wanted to ask if someone knows already which changes are necessary, or what is the best, correct way to create an ObjectID field in a Pydantic v2 schema.

Thanks in advance!

Hi @CarlosDC, I don’t believe any changes will be required, based on the FastAPI migration guide and running bump-pydantic --diff on the source code in the blog post.

1 Like

I get an error message when I try to use the described “PyObjectId” class.

“The __modify_schema__ method is not supported in Pydantic v2. Use __get_pydantic_json_schema__ instead.”

To anyone searching for a solution to the problem, please look at this answer in S.O.
It worked for me :slight_smile:

https://stackoverflow.com/a/76837550

1 Like

Hello,
I’ve also encountered this error and the solution of @CarlosDC is working but the behavior is different from the previous version of the guide. This causes also an issue with finding the correct DB entries to delete, because the ID’s are not the “same” anymore.

When I’m using the exact code from the guide I also get the error: “pydantic.errors.PydanticUserError: The __modify_schema__ method is not supported in Pydantic v2. Use __get_pydantic_json_schema__ instead.”

When I try the suggested solution on stackoverflow I’ve noticed that the _id attribute is no longer a string but it’s stored as an ObjectId('6501....'). When I try to use the ID as a string it no longer finds the DB entry.
This breaks the old way it was used and renders the guide incorrect.

Any suggestions how to fix this to get the old behavior?

Thanks in advance!

Starting from Pydantic 2.4, the solution in the next link worked great for me, fixing also the problem that FastAPI was unable to generate the OpenAPI documentation when using the previous workaround.

1 Like