If you’re working with FastAPI and PyMongo, it is very likely that you are greeted with:
ValueError: [TypeError("'ObjectId' object is not iterable"), TypeError('vars() argument must have __dict__ attribute')]
As you may know, every document in MongoDB has an _id
attribute (a primary key). When you retrieve a document with PyMongo and you return the dictionary, FastAPI cannot serialize _id
(which is of type bson.objectid.ObjectId
). If you look around there are a number of solutions to this. Check them out, as they might be more appropriate for your case. However, one particular workaround, namely doing a document.pop('_id', None)
before returning the dictionary got me thinking. So for my particular case I tried:
:
id = bucket_list.insert_one(document).inserted_id
# document.pop('_id', None)
document["_id"] = f'{id}'
:
which worked find for my use-case.