ObjectId handling by msgpack in MongoDb checkpointer

When using MongoDb and so mongo chekpointing, I often find myself having bson ObjectId in my state. But serde and msgpack don’t handle these types and so raise an error at line 482 of langgraph/checkpoint/serde/jsonplus.py.

Right now langgraph don’t have bson as a dependency which prompt me to say that the handling of ObjectId won’t (and shoudn’t) be handled there . But I haven’t really found a good solution to circumvent this.

Is there a way I havent found to handle it without having to patch the method manually like mentioned in this issue ?

hi @JuR-0

have you tried with this node?

convert ObjectId to str at the boundary - right where your MongoDB queries feed data into the graph state. This avoids serialization issues entirely and keeps your state portable across different checkpointer backends.

from bson import ObjectId

def query_mongo_node(state):
    """Node that queries MongoDB and normalizes ObjectIds."""
    doc = collection.find_one({"_id": ObjectId(state["doc_id"])})

    # Convert ObjectId fields to strings before returning to state
    if doc and "_id" in doc:
        doc["_id"] = str(doc["_id"])

    return {"document": doc}

OR

For deeply nested documents, a recursive helper:

from bson import ObjectId

def convert_objectids(obj):
    """Recursively convert all ObjectId instances to strings."""
    if isinstance(obj, ObjectId):
        return str(obj)
    elif isinstance(obj, dict):
        return {k: convert_objectids(v) for k, v in obj.items()}
    elif isinstance(obj, list):
        return [convert_objectids(item) for item in obj]
    return obj

def query_mongo_node(state):
    doc = collection.find_one({"_id": ObjectId(state["doc_id"])})
    return {"document": convert_objectids(doc)}

Another ways would be:

  • custom serializer with objectId support
  • pydantic state model with validator