Skip to content

# Multi Model

### Use Case 6: Multi-Model Service with Registration

Scenario: Complete microservice with multiple related models.

Python

    from mongo_ops import (
        MongoConnectionManager,
        BaseDocument,
        BaseRepository,
        ModelRegistry
    )
    from fastapi import FastAPI
    from contextlib import asynccontextmanager

    # Define Models
    class User(BaseDocument):
        username: str
        email: str
        role: str = "user"

    class Post(BaseDocument):
        title: str
        content: str
        author_id: str
        likes: int = 0

    class Comment(BaseDocument):
        post_id: str
        user_id: str
        content: str

    # Define Repositories
    class UserRepository(BaseRepository[User]):
        def __init__(self):
            super().__init__("users", User)

    class PostRepository(BaseRepository[Post]):
        def __init__(self):
            super().__init__("posts", Post)

    class CommentRepository(BaseRepository[Comment]):
        def __init__(self):
            super().__init__("comments", Comment)

    # Register all models
    ModelRegistry.register("users", User, indexes=[("email", 1), ("username", 1)])
    ModelRegistry.register("posts", Post, indexes=[("author_id", 1), ("created_at", -1)])
    ModelRegistry.register("comments", Comment, indexes=[("post_id", 1), ("user_id", 1)])

    # Setup FastAPI with lifespan
    @asynccontextmanager
    async def lifespan(app: FastAPI):
        await MongoConnectionManager.connect(
            uri="mongodb://localhost:27017",
            db_name="social_app"
        )
        await ModelRegistry.initialize_all()
        yield
        await MongoConnectionManager.disconnect()

    app = FastAPI(lifespan=lifespan)

    # Initialize repositories
    user_repo = UserRepository()
    post_repo = PostRepository()
    comment_repo = CommentRepository()

    # Endpoints
    @app.post("/users/", response_model=User)
    async def create_user(user: User):
        return await user_repo.create(user)

    @app.post("/posts/", response_model=Post)
    async def create_post(post: Post):
        return await post_repo.create(post)

    @app.post("/comments/", response_model=Comment)
    async def create_comment(comment: Comment):
        return await comment_repo.create(comment)