← 中文资源

简体中文版本

Beanie

基于 Motor 与 Pydantic 的 Python 异步 MongoDB ODM,提供类型化文档与查询 API,适合 FastAPI。

阅读英文原文

概述

Beanie 提供异步 MongoDB 类型化 ODM 的能力。本参考列出最常用的核心 API 与典型用法,帮助你快速上手并在生产环境中安全使用。

核心 API

  • init_beanie:签名与典型用法见下方代码示例。
  • Document.insert:签名与典型用法见下方代码示例。
  • Document.find:签名与典型用法见下方代码示例。

代码示例

from beanie import init_beanie
from motor.motor_asyncio import AsyncIOMotorClient

client = AsyncIOMotorClient("mongodb://localhost:27017")
await init_beanie(database=client.app, document_models=[User])

使用注意

需要异步上下文,应在事件循环内使用。Pydantic 校验在建模型时运行,可尽早发现结构错误。

验证方式

插入一个文档并确认返回实例带有生成的 id,再用字段条件查回它。