I have a serverless application written in Scala.js that is writing to a MongoDb database. We wrote our own custom integration with the Node.js mongodb driver. Everything is working well except for date objects. I am attempting to find a way to serialize my objects so that mongo can interpret them as a date object, rather than a string.
Without getting to much in detail, the code uses Circe Encoders to serialize the objects to Json. Here is the encoder I am using for the date object:
implicit val dateEncoder: Encoder[Date] = Encoder.encodeJson.contramap[Date] {
date =>
Json.obj(
"$date" -> Json.fromString(date.toISOString())
)
}
The Circe Json then gets converted to Scala.js Json before interacting with the Node.js driver.
In the encoder above, I am attempting to replicate the bson format of date objects that I see in this documentation. Conceptually, it is working correctly, as I see the object is being saved with this value:
{
"_id" : "test-id",
"profile" : {
"IndividualProfile" : {
"username" : "[email protected]",
"dateCreated" : {
"$date" : "2024-06-17T15:50:12.059Z"
},
"dateUpdated" : {
"$date" : "2024-06-17T15:50:12.059Z"
}
}
}
}
You can see the dateCreated and dateUpdated objects in the result, and they appear to have the json formatted as intended, but mongo is not interpreting the field as a date object: it’s just an object with a nested string field.
I get this is probably a nice use case, but I was curious if anyone had an idea what I might be missing here?
mongosh?Json.objlooks to me as a function which creates a JSON-Object rather than aDatePerhaps it would be simpledate => new Date(Json.fromString(date.toISOString()))or similar. But it would be pointless anyway, because you convert aDateinto a string and then back again into aDate. Try even simplerdate => date, there is no reason the convert between string andDateforth and back.datetype (or otherwise).EJSONserialize and deserialize functions. So effectively, I am building out the correct structure, serializing it into bson, and then saving that. It now shows up in MongoDb as a date object, so I'm satisfied