0PricingLogin
FastAPI Backend Development Bootcamp · Lesson

Document Modeling with Beanie ODM

Define typed document models, indexes, and embedded structures using Beanie on top of Pydantic.

What Beanie Brings to FastAPI

Beanie is an asynchronous ODM (Object-Document Mapper) for MongoDB built directly on top of Pydantic and the async motor driver. In a FastAPI backend it gives you typed, validated documents that feel just like the Pydantic models you already use for request and response bodies.

  • Each document class maps to one MongoDB collection.
  • Each instance maps to one document (a JSON-like record).
  • Validation, serialization, and JSON Schema come for free from Pydantic v2.

Because everything is async, Beanie pairs naturally with FastAPI's async route handlers and avoids blocking the event loop on database I/O.

Your First Document Model

A Beanie model subclasses Document instead of Pydantic's BaseModel. Fields are declared with normal type hints, and Beanie automatically gives every document an id field backed by MongoDB's _id (an ObjectId).

  • Required fields have no default; optional fields use Optional[...] or a default value.
  • The collection name is derived from the class name unless you override it.

Below, Product becomes a collection of product documents.

from typing import Optional
from beanie import Document


class Product(Document):
    name: str
    price: float
    description: Optional[str] = None
    in_stock: bool = True


# An instance is just a validated Pydantic object until you insert it
item = Product(name="Keyboard", price=49.9)
print(item.name, item.price, item.in_stock)

All lessons in this course

  1. Async MongoDB Access with Motor
  2. Document Modeling with Beanie ODM
  3. Aggregation Pipelines and Complex Queries
  4. Schema Evolution and Document Migrations
← Back to FastAPI Backend Development Bootcamp