Uploaded image for project: 'Python Driver'
  1. Python Driver
  2. PYTHON-3395

Make ObjectId properly convert when being served from a rest API

    • Type: Icon: Improvement Improvement
    • Resolution: Won't Fix
    • Priority: Icon: Minor - P4 Minor - P4
    • None
    • Affects Version/s: None
    • Component/s: BSON
    • None

      When serving data through Rest APIs the ObjectId has to be converted (to a dict when serving JSON) every time, which adds the complexity of needing to change/parse it and also could potentially slow the API when there is a lot of data to send. And although adding a function to convert the ObjectId to a dictionary doesn't follow the guidelines, It would be a great quality of life improvement. I've made already a working solution for this and works fine when sending the data using FastApi.

      My solution was to:

      • Add _dict_ attribute to _slots_
      __slots__ = ("__id", "__dict__")
      
      • Set _dict attribute to be self._id
      # This is were self.__id is set.
      if oid is None:
                  self.__generate()
              elif isinstance(oid, bytes) and len(oid) == 12:
                  self.__id = oid
                  self.__dict__ = {"$oid": binascii.hexlify(self.__id).decode()} # my changes
              else:
                  self.__validate(oid)
      

       
       

       

            Assignee:
            shane.harvey@mongodb.com Shane Harvey
            Reporter:
            ticua@ticua.ar ticua ticua
            Votes:
            0 Vote for this issue
            Watchers:
            4 Start watching this issue

              Created:
              Updated:
              Resolved: