MongoModel
The MongoModel, one of the core classes in this package, serves as a Pydantic model that extends Pydantic's BaseModel with additional fields. This model is instrumental in defining the structure of MongoDB documents and generating the OpenAPI schema for your routes.
Being a Pydantic model, the MongoModel inherits all functionalities of Pydantic models, including the use of the Pydantic Field class for defining model fields. However, the MongoModel introduces several supplementary fields to the Pydantic model.
To utilize the MongoModel, you can import it from the fastapi_crudrouter_mongodb package. This grants access to all methods available in Pydantic models as well as those specific to the MongoModel, which will be outlined below.
Method | Description | State |
---|---|---|
from_mongo | Transform a MongoDB object to a python dict (as a MongoModel) | OK |
mongo | Convert a MongoModel object to a dict | Deprecated |
to_mongo | Same as mongo but with better naming | OK |
convert_to | Gives you the oportunity to convert a MongoModel to any other Pydantic dict or MongoModel | Ok |
The MongoModel validate the following field in the Pydantic model
id: Annotated[ObjectId, MongoObjectId] | None = None
The id field is an optional field that is used to store the id of the document in the database. It is an instance of the MongoObjectId class, which is a subclass of the bson
ObjectId class. The id field is automatically generated by the database when you create a new document.
It will be automatically translated to an "_id" in MongoDB, and returned as "id" in the response to match the RESTfull specifications.
Make sure to build your model like below
class MyModel(MongoModel):
id: Annotated[ObjectId, MongoObjectId] | None = None
my_field: str
Further details are available in the following links.
- For Pydantic v1.x : Github
- For Pydantic v2.x : Stackoverflow