FastAPI, PyMongo and ‘ObjectId’ object is not iterable.

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.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s