‘ObjectId’ object is not iterable
If you use fastapi, when the return result contains the id of mongodb, which is the ObjectId type, the error message will be reported: TypeError("‘ObjectId’ object is not iterable").
A direct Google search can be used to get several methods:
- Use the str() method to convert the ObjectId to a string
- Use the built-in json_util.dumps() method of bson to convert the ObjectId to a string
- Delete the ObjectId field
- Define a JSONEncoder class to convert the ObjectId to a string
- json.dumps(my_obj, default=str)
- If it is an older version of fastapi
It seems that the 6th method is more elegant, but it does not work for the return results that do not use pydantic. Also, the new version of pydantic doesn’t work that way.
In fact, no matter what type, as long as it is not supported by JSON, an error will be reported, such as the datetime type. But why doesn’t fastapi report an error when it returns the datetime type? This is because FastAPI has done the internal processing to convert the datetime type to the string type.
Through the error message.
We can see that the error is reported in the fastapi encoders.py.
Open encoders.py file, you can see
It’s a bit familiar, it’s similar to JSONEncoder, but it’s an internal implementation of fastapi. A little glance at the code shows that:
|
|
This is the internal processing method of fastapi, which converts unsupported types into supported types through the corresponding processing methods.
So, we get a relatively simple way to deal with it. Before the program starts, add the ObjectId type to the ENCODERS_BY_TYPE and call the str method to convert.
In this way, the problem of fastapi returning an ObjectId type can be solved. If there are other types to be processed, you can also do the same.
fastapi==0.111.0