Home:ALL Converter>Transform Mongo Document to predefined Type

Transform Mongo Document to predefined Type

Ask Time:2022-03-24T16:49:08         Author:user17526539

Json Formatter

By default, mongodb uses its mapper to convert the result of a query from type Document to my predefined Type.

the _id fields are stored in ObjectId format, if the predefined result type contains a string type field id, then mongo will rename the fied from _id to id, and will transform the ObjectId type to String.

mongo will do the same for other custom types. for example, I have a LatLng object, I created a custom converter that transforms this object into an array in Write operations, and transforms the array into a LatLng object in read operations.

the question here is how to use the same converter to transform a document to my predefined type without the result being returned from mongo.

i have this object

{
  "_id": {
    "timestamp": 1641203767,
    "date": "2022-01-03T09:56:07.000+00:00"
  },
  "state": "VALIDATED",
  "phone": "999999999",
  "latLng": [
    0.0,
    0.0
  ]
}

I want to transform it to this object (as mongo does automatically during read requests)

{
  "id": "xxxxxxxxx",
  "state": "VALIDATED",
  "phone": "999999999",
  "latLng": {
    "latitude": 0.0,
    "longitude": 0.0
  }
}

Author:user17526539,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/71599391/transform-mongo-document-to-predefined-type
yy