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

使用FastAPI操作MongoDB时查询集合返回空列表问题

问题:FastAPI结合MongoDB获取集合数据返回空列表

使用FastAPI结合MongoDB开发时,调用获取ads集合所有数据的接口返回空列表,但数据库中已存在数据。以下是相关代码及数据库情况:

相关代码

database.py

client = MongoClient("url")
selldei_db = client["selldei"]
ads_collection = selldei_db["ads"]

models.py

class Ads(BaseModel):
      ads_title: str
      ads_description: str
      is_published: bool = False

schemas.py(注:原文件名拼写错误为schameas.py)

def ads_serializer(single_ads) -> dict:
    return{
        "ads_title": single_ads["ads_title"],
        "ads_description":single_ads["ads_description"],
        "is_published": single_ads["is_published"]
    }

def ads_list_serializer(ads_list)-> list:
    return [ads_serializer(single_ads) for ad in ads_list]

路由代码

@router.get('/all_ads')
def all_ads():
    ads =  ads_list_serializer(ads_collection.find())
    return ads

@router.post('/post_ads/')
def ads_post(ads:Ads):
    ads = ads_collection.insert_one(dict(ads))
    return {"status":"success"}

数据库情况

数据库截图显示:MongoDB的selldei数据库下的ads集合中已有一条数据,包含ads_title、ads_description、is_published字段。

问题分析与解决方案

1. 序列化函数变量名错误

ads_list_serializer函数中的列表推导式存在变量名错误:循环遍历的变量是ad,但传入ads_serializer的却是函数参数single_ads,导致没有正确遍历集合中的数据。

修复后的ads_list_serializer:

def ads_list_serializer(ads_list)-> list:
    return [ads_serializer(ad) for ad in ads_list]

2. 新增数据路由的集合调用错误

原ads_post路由中使用selldei_db.ads_collection.insert_one,但selldei_db中并没有名为ads_collection的集合,正确的调用应该使用database.py中已定义的ads_collection变量。同时修正了返回状态的拼写错误(sucess→success)。

修复后的ads_post路由:

@router.post('/post_ads/')
def ads_post(ads:Ads):
    ads_collection.insert_one(dict(ads))
    return {"status":"success"}

3. 可选:显式转换游标为列表

MongoDB的find()方法返回的是游标对象,虽然列表推导式可以遍历游标,但显式转换为列表更直观,也避免潜在的遍历问题:

@router.get('/all_ads')
def all_ads():
    ads = ads_list_serializer(list(ads_collection.find()))
    return ads

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 13:35:33