Automatic conversion of object id

When objects with ObjectIds are passed from my flask python backend to the frontend, I use “dumps” to build the json. Therefore the object ids sent end up like:
{“$oid”: “663a00abb019ddc0a8dbe9c0”}

On the frontend, I then build a new object that links to that oid object:
{ userId: {“$oid”: “663a00abb019ddc0a8dbe9c0”}, … }
and send as a POST request.

The backend then stores that new object, but it stores the $oid object instead of it automatically converting it back into an ObjectId.

I don’t want to manually have to convert back into an ObjectId, as it is onerous to do that for every type of api request, and also gets trickier when deeper tree structures contain ids that then also need to be conveted.

How can this be done? Otherwise how is it normally done?

The backend should parse the inputed JSON as MongoDB Extended JSON using json_util.loads().

2 Likes

Thanks Shane.
Yes, by doing the following, it worked.

from bson.json_util import loads
@app.route(“/some-endpoint”, methods=[“POST”])
def some_handler():
data = loads(request.data)