Search code examples
pythonmongodbpymongofastapi

Python mongodb/motor "'ObjectId' object is not iterable" error while trying to find item in collection


I know that there are similar questions, but I've tried everything that was advised and still getting an error. I'm trying to fetch item from mongo collection by id, converting string to an ObjectId, like that:

from bson import ObjectId


async def get_single_template(db, template_id):
    template = await db.templates.find_one({ '_id': ObjectId(template_id) })
    return template

And I'm getting an error:

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

"template_id" is a valid string, like "601401887ecf2f6153bbaaad". ObjectId created from it - too. It fails only to work inside find_one() method. When I'm using find() with that id it works well. I've tried from bson.objectid import ObjectId too - no difference. I'm using motor library to access mongo. Is there something that I'm missing?

P.S. Links to the corresponding docs:

https://pymongo.readthedocs.io/en/stable/tutorial.html#querying-by-objectid

Though I'm using motor async library, I can't find direct examples in it's docs. Basically, it wraps pymongo. I can only find examples in other's source code.


Solution

  • Well, I've found out what caused that issue. The problem was not in the way I've tried to query data, but in the way I've tried to return it. I've forgotten to convert ObjectId to string in the entity that I've retrieved from database and tried to return it 'as is'. My bad.