Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

308
Views
How can I get more than one document from mongodb with fastapi?

my db model looks like this...

from pydantic import BaseModel

class Store(BaseModel):
    name: str
    store_code : str

and there can be same store names in db with different store_code. what I want is filtering all informations of stores with same names. for example, if my db is like this...

{
name:lg
store_code: 123

name:lg
store_code:456
}

I'd like to see all those two documents my python fast api code is like this..

from fastapi import FastAPI, HTTPException
from database import *
app = FastAPI()

@app.get("/api/store{store_name}", response_model=Store)
async def get_store_by_name(store_name):
    response = await fetch_store_by_name(store_name)
    if response:
        return response
    raise HTTPException

and this is my mongo query code...

from pymongo import MongoClient
from model import Store

client = MongoClient(host='localhost', port=27017)


database = client.store

async def fetch_store_by_name(store_name:str):
    document = collection.find({"name":store_name})
    return document

i thought in the document, there would be two documents eventually. but there's always an error like this

pydantic.error_wrappers.ValidationError: 1 validation error for Store
response
  value is not a valid dict (type=type_error.dict)

is there anyone to help me please?

++++

I just changed my query like this

async def fetch_store_by_name(store_name:str):
    stores = []
    cursor = collection.find({"name":store_name})
    for document in cursor:
        stores.append(document)
    return stores

this should returns two documents like I expected but it still has

ValueError: [TypeError("'ObjectId' object is not iterable"), TypeError('vars() argument must have __dict__ attribute')]

this error.

I think my fast-api code has a problem which I really have no idea...

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

async def fetch_store_by_name(store_name:str):
stores = []  ---Fault in this line---  
cursor = collection.find({"name":store_name})
for document in cursor:
    stores.append(document)
return stores

stores should be a string value, not a list as Mongodb will try to find it as the default value that you provided. In this case - str

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!