Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"ObjectId' object is not iterable" error, while fetching data from MongoDB Atlas

Okay, so pardon me if I don't make much sense. I face this 'ObjectId' object is not iterable whenever I run the collections.find() functions. Going through the answers here, I'm not sure where to start. I'm new to programming, please bear with me.

Every time I hit the route which is supposed to fetch me data from Mongodb, I getValueError: [TypeError("'ObjectId' object is not iterable"), TypeError('vars() argument must have __dict__ attribute')].

Help

like image 215
nathanielsenje Avatar asked Sep 14 '20 09:09

nathanielsenje


2 Answers

I was having a similar problem to this myself. Not having seen your code I am guessing the traceback similarly traces the error to FastAPI/Starlette not being able to process the "_id" field - what you will therefore need to do is change the "_id" field in the results from an ObjectId to a string type and rename the field to "id" (without the underscore) on return to avoid incurring issues with Pydantic.

like image 147
James Harrison Avatar answered Sep 19 '22 07:09

James Harrison


Exclude the "_id" from the output.

result = collection.find_one({'OpportunityID': oppid}, {'_id': 0})
like image 45
AlbaOpus Avatar answered Sep 17 '22 07:09

AlbaOpus