'FastAPI + MongoDB ValueError: [TypeError("'ObjectId' object is not iterable")

I try to insert data to my MongoDB Database after scraping data. I did the exact same thing with NodeJS and Express, now I'm testing FastAPI.

URI = '...'
try: 
    client = MongoClient(URI)
    print("Connected successfully!!!")
except:
    print("Could not connect to MongoDB")

db = client.myDatabase
collection = db.myCollection

...

    @app.get("/api/{country_name}/{city_name}")
    async def read_item(country_name: str,city_name: str, username: str =Depends(get_current_username)):
    data = await scraper.scrapeData(country_name, city_name)
    collection.insert_one(data)
    return data

The object I get returned from my scraper looks like this

    data = {
    "city":"city",
    "object":{
        "key": value,
    },
    "object":{
        "key: value,
    },
    "object":{
        "key": value
    },
    "timestamp":"06-05-2022"
}

The data will be inserted into my database, but while inserting I get the error

ERROR:    Exception in ASGI application

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

This what I get back from scrapeData():

data = {
    "city":"Stuttgart",
    "programmingLangs":{
        "Java":2247,
        "JavaScript":1227,
        "Python":1001,
        "Kotlin":235,
        "C":325,
        "C++":442,
        "C#":567,
        "Go":946,
        "Rust":20,
        "Visual Basic":36,
        "PHP":514,
        "Delphi":33,
        "Swift":100,
        "Ruby":56,
        "Perl":48,
        "Lua":13
    },
    "frameworks":{
        "Angular":459,
        "React":579,
        "Vue":277,
        "ASP NET":78,
        "Django":28,
        "jQuery":87,
        "Spring":413,
        "Laravel":97
    },
    "categories":{
        "DevOps":954,
        "Web Developer":626,
        "Backend Developer":507,
        "Frontend Developer":366,
        "Fullstack Developer":144,
        "Data Scientist":3333,
        "Game Developer":3333,
        "Mobile Developer":3333
    },
    "timestamp":"06-05-2022"
}

Weird thing is when I store this in variable and inserted this way, I get no errors.

Edit

I tried it with some dummy Data like:

document1 = {
    "name":"John",
    "age":24,
    "location":"New York"
    }

So it's not about the data, I still get the same error. Any help would be much appreciated.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source