sthomps
sthomps

Reputation: 4840

How to JSON transform a date to BSONDateTime?

I have a controller that receives a JSON body. One of the fields is a Date of the form yyyy-mm-dd. What I would like to do is transform this field to a format suitable for a BSONDateTime and have ReactiveMongo perform the insert.

I think something like:

((__ \ 'myDate).json.pickBranch(Reads.of[JsString] andKeep toDateFormat))

How can I do this transformation?

Upvotes: 2

Views: 1578

Answers (1)

sthomps
sthomps

Reputation: 4840

A step towards progress... I believe I can do something as follows to get the date string into a JsNumber which reactive mongo can then handle:

((__ \ 'myDate).json.update(Reads.of[DateTime].map{ x => JsNumber(x.getMillis)}) )

It turns out Play has some implicits to handle Date and DateTime objects in the Reads class.. so doing Reads.of[DateTime] works.

UPDATE:

To get this working with the Play-ReactiveMongo implicit BSON converters you need to create a JsObject with a "$date" key as follows:

((__ \ 'tripDate).json.pickBranch(Reads.of[DateTime].map{ x => Json.obj("$date"->JsNumber(x.getMillis))}) )

Upvotes: 3

Related Questions