Make ObjectId properly convert when being served from a rest API

XMLWordPrintableJSON

    • Type: Improvement
    • Resolution: Won't Fix
    • Priority: Minor - P4
    • None
    • Affects Version/s: None
    • Component/s: BSON
    • None
    • None
    • None
    • None
    • None
    • None
    • None
    • 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
            Reporter:
            ticua ticua
            Votes:
            0 Vote for this issue
            Watchers:
            4 Start watching this issue

              Created:
              Updated:
              Resolved: