ReactiveMongo/Play-ReactiveMongo

Saving doc with $date field yields DatabaseException

Closed this issue · 2 comments

I have the following model case class:

case class WorkItem(duration: Period, date: org.joda.time.LocalDate, description: String)

serialized to JSON using this Writes[WorkItem]:

implicit val workItemWrites = new Writes[WorkItem] {
def writes(workItem: WorkItem) = Json.obj(
"duration" -> JsString(workItem.duration.toString(timeParser)),
"$date" -> JsNumber(workItem.date.toDateTimeAtCurrentTime.getMillis),
"description" -> JsString(workItem.description)
)
}

When i try to persist this using reactivemongo play:
val json = Json.toJson(workItem)
collection.save(json)

I get the following exception:

Execution exception[[LastError: DatabaseException['Document can't have $ prefixed field names: $date' (code = 2)]]]

Looking into the plugins BSONFormats source "$date" fields with JSNumber type should be converted to BSONDateTime properly. I use the following import:
import play.modules.reactivemongo.json.BSONFormats._

Am i missing something or is this a bug?

try it with
"date"->Json.obj("$date" -> JsNumber(workItem.date.toDateTimeAtCurrentTime.getMillis))

Closing since @critikaled answered the question :)