Home > OS >  How to cache bson ObjectId
How to cache bson ObjectId

Time:09-04

I have a question regarding ObjectId caching.

I am caching mongoDB document using redis, and when I check the cached value, only the timeStamp and date of the ObjectId are cached as shown below, and they are being retrieved with values different from the ObjectId of the actual document.

"id":{
  "@class":"org.bson.types.ObjectId",
  "timestamp":1658025133,
  "date":["java.util.Date",1658025133000]
},

Actual ObjectId: 6311ba39c31566544746d31b

ObjectId retrieved as cached result: 6311ba3911d1d82cb7892c73

How can I cache it so that it is fetched as an actual ObjectId value?

CodePudding user response:

You need to add custom serializer to serialize ObjectId into String

@JsonComponent
class ObjectIdSerializer : StdSerializer<ObjectId>(ObjectId::class.java) {
  override fun serialize(value: ObjectId, gen: JsonGenerator, provider: SerializerProvider) {
    return gen.writeString(value.toString())
  }
}

Then

objectMapper().registerModule(SimpleModule().addSerializer(ObjectIdSerializer()))
  • Related