[Python] FastAPI issues with MongoDB - TypeError: 'ObjectId' object is not iterable

Discussão em 'Python' iniciado por Stack, Abril 13, 2025.

  1. Stack

    Stack Membro Participativo

    I am having some issues inserting into MongoDB via FastAPI.

    The below code works as expected. Notice how the response variable has not been used in response_to_mongo().

    The model is an sklearn ElasticNet model.

    app = FastAPI()


    def response_to_mongo(r: dict):
    client = pymongo.MongoClient("mongodb://mongo:27017")
    db = client["models"]
    model_collection = db["example-model"]
    model_collection.insert_one(r)


    @app.post("/predict")
    async def predict_model(features: List[float]):

    prediction = model.predict(
    pd.DataFrame(
    [features],
    columns=model.feature_names_in_,
    )
    )

    response = {"predictions": prediction.tolist()}
    response_to_mongo(
    {"predictions": prediction.tolist()},
    )
    return response


    However when I write predict_model() like this and pass the response variable to response_to_mongo():

    @app.post("/predict")
    async def predict_model(features: List[float]):

    prediction = model.predict(
    pd.DataFrame(
    [features],
    columns=model.feature_names_in_,
    )
    )

    response = {"predictions": prediction.tolist()}
    response_to_mongo(
    response,
    )
    return response


    I get an error stating that:

    TypeError: 'ObjectId' object is not iterable


    From my reading, it seems that this is due to BSON/JSON issues between FastAPI and Mongo. However, why does it work in the first case when I do not use a variable? Is this due to the asynchronous nature of FastAPI?

    Continue reading...

Compartilhe esta Página