You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Pydantic模型中使用MongoDB的ObjectId

改用MongoDB ObjectId替代UUID的方案

要把模型里的UUID换成MongoDB的ObjectId,按以下步骤操作:

  1. 确保安装依赖
    如果还没装pymongo,先执行安装命令:
pip install pymongo
  1. 导入必要模块
    在你的模型文件里,导入bson的ObjectId以及Pydantic的相关工具:
from bson import ObjectId
from pydantic import BaseModel, Field, BeforeValidator, PlainSerializer
from typing import Annotated
  1. 定义适配Pydantic的ObjectId类型(可选但更规范)
    封装一个可复用的类型,自动处理前后端的ID转换:
MongoObjectId = Annotated[
    ObjectId,
    BeforeValidator(lambda x: ObjectId(x) if isinstance(x, str) else x),
    PlainSerializer(lambda x: str(x), return_type=str)
]

这个类型会自动完成:

  • 前端传入字符串ID时,转为MongoDB的ObjectId
  • 返回响应时,把ObjectId转为字符串(避免序列化失败)
  1. 修改模型字段
    替换原来的UUID字段,设置default_factory=ObjectId生成原生MongoDB ID:
class YourModel(BaseModel):
    id: MongoObjectId = Field(default_factory=ObjectId, alias="_id")
    # 其他字段...

    class Config:
        populate_by_name = True  # 允许通过别名"_id"填充字段

如果不想单独定义类型,也可以直接写在字段里:

id: Annotated[
    ObjectId,
    BeforeValidator(lambda x: ObjectId(x) if isinstance(x, str) else x),
    PlainSerializer(lambda x: str(x), return_type=str)
] = Field(default_factory=ObjectId, alias="_id")

修改完成后,模型生成的_id就是MongoDB原生的ObjectId,同时能正常处理前后端的字符串ID交互。

内容的提问来源于stack exchange,提问作者raju

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 18:38:10