MongoObjectId¶
MongoObjectId is a Pydantic annotation for MongoDB ObjectIds. It enables proper serialization, validation, and OpenAPI documentation for MongoDB's unique identifiers.
What It Does¶
MongoObjectId:
- validates that a field contains a valid BSON ObjectId
- automatically converts between ObjectId and JSON strings (for API responses)
- generates correct OpenAPI schema documentation
- handles the
_id↔idfield aliasing so you can useidin Python code
Two Ways to Use It¶
Option 1: Full Annotation (Explicit)¶
from typing import Annotated
from fastapi_crudrouter_mongodb import MongoModel, MongoObjectId, ObjectId
class UserModel(MongoModel):
id: Annotated[ObjectId, MongoObjectId] | None = None
Option 2: Type Alias (Simpler)¶
For convenience, use the ObjectIdType alias:
from fastapi_crudrouter_mongodb import MongoModel, ObjectIdType
class UserModel(MongoModel):
id: ObjectIdType | None = None
Both approaches work identically—choose whichever reads clearer to you.
Primary Key Fields¶
Use MongoObjectId for the id field on any MongoModel:
from fastapi_crudrouter_mongodb import MongoModel, ObjectIdType
class UserModel(MongoModel):
id: ObjectIdType | None = None # Primary key, auto-generated by MongoDB
name: str
email: str
The None default tells MongoDB to auto-generate the id when creating a new document.
Foreign Key Fields¶
Use MongoObjectId for reference fields that point to other documents:
from fastapi_crudrouter_mongodb import MongoModel, ObjectIdType
class CommentModel(MongoModel):
id: ObjectIdType | None = None
text: str
user_id: ObjectIdType # Foreign key reference (not optional)
class PostModel(MongoModel):
id: ObjectIdType | None = None
title: str
author_id: ObjectIdType # Foreign key reference (not optional)
Foreign key fields are not optional because they must reference an existing document.
How ID Aliasing Works¶
MongoDB stores primary keys as _id, but APIs usually expose them as id for simplicity. MongoObjectId handles this automatically:
# In your code: use "id"
user = UserModel(id=None, name="Alice")
print(user.id) # ObjectId or None
# In MongoDB: stored as "_id"
db.users.insert_one({"_id": ObjectId(...), "name": "Alice"})
# In API response: returned as "id"
{
"id": "507f1f77bcf86cd799439011", # JSON string for REST
"name": "Alice"
}
No manual conversion needed—MongoObjectId handles it all.
Summary¶
- Use
ObjectIdType(orAnnotated[ObjectId, MongoObjectId]) for any id field - Primary keys: make them optional with
| None = Nonefor auto-generation - Foreign keys: keep them required (no
| None) to ensure references exist - Let MongoObjectId manage the
_id↔idconversion automatically