格式化从scala表单获取的json对象中的日期以插入MongoDb

时间:2018-04-27 16:17:44

标签: json mongodb forms scala date

我一直在尝试将结果从scala form(映射到类模型)转换为json object,以便将此数据插入到(Mongo数据库)集合中。我正在使用 Play Framework ReactiveMongo插件(启用JSON而不是BSON)。模型和表单如下所示:

   case class LastVisit(selection: String = "", date: Option[Date] = None) extends ReadAndWriteTrait

   case class AdminM(_id: Option[BSONObjectID], adminCreatedId: Option[Int], dateCreated: Option[Date], adminModifiedId: Option[Int], lastModified: Option[Date]) extends ReadAndWriteTrait

   case class MyClass(usrId: Option[BSONObjectID] = None, numOfVisits: Option[Int] = None, lastVisit_e: Option[LastVisit] = None, admin_e: Option[AdminM]) extends SuperVarT with ReadAndWriteTrait

   object MyClass extends SuperFormT with ReadAndWriteTrait {

     implicit val lastVisitFormat: OFormat[LastVisit] = Json.format[LastVisit]
     implicit val adminMFormat: OFormat[AdminM] = Json.format[AdminM]
     implicit val myClassFormat: OFormat[MyClass] = Json.format[MyClass]

     val form = Form(
       mapping(
         "usrId" -> optional(
            text.transform(str2bson, bson2str)
         ),
         "numOfVisits" -> optional(number),
         "lastVisit_e" -> optional(mapping(
            "selection" -> nonEmptyText,
            "date" -> optional(date)
         )(LastVisit.apply)(LastVisit.unapply)),
         "admin_e" -> optional(mapping(
             "_id" -> ignored(Option.empty[BSONObjectID]),
            "adminCreatedId" -> optional(number),
            "dateCreated" -> optional(date),
            "adminModifiedId" -> optional(number),
            "lastModified" -> optional(date).transform(date2Date, date2NowDate)
         )(AdminM.apply)(AdminM.unapply))
       )(MyClass.apply)(MyClass.unapply)
     )

     trait ReadAndWriteTrait {

       implicit val dateRead: Reads[Date] = (__ \ "$date").read[Long].map { 
          date => new Date(date)
       }

       implicit val dateWrite: Writes[Date] = new Writes[Date] {
         def writes(date: Date): JsValue = Json.obj(
            "$date" -> date.getTime
         )
       }

     }

令人沮丧的是,lastVisit_e.date字段作为Long类型而不是ISODate("date here")插入到数据库中 - 在Json中,Json.obj(s"$$date" -> JsNumber(dateLong here))Action }} 状态。这是我正在路由的 def updateFromForm(collName: String, oId: Option[BSONObjectID], activeTabIdx: Int = 0) = Action.async { implicit request: Request[AnyContent] => MyClass.form.bindFromRequest.fold( errorForm => Future.successful(Ok("TODO")), data => { /* // todo - uncomment when formatting is correct val doc = apiC.prepareData(data) // function used to transform/prepare data update(collName, oId, doc, activeTabIdx)(request) // function to be called to update db collection */ val doc = Json.toJson(doc) // for test purposes Future(Ok(doc.toString())) // for test purposes } ) } 函数,用于将表单中的数据更新到 Mongo Collection 。我刚刚定制它给我一个输出,以便我可以看到日期格式不正确:

   {
      "usrId":{
         "$oid":"5a28258d9830b7614f566cc7"
      },
     "numOfVisits":5,
     "lastVisit_e":{
        "selection":"departure date",
        "date":1496271600000
      }
   }

这是我得到的典型回应:

usrId

$oid: "5a28258d9830b7614f566cc7"输出正确(lastVisit_e.date)但Long显示为#!/bin/sh # Extract the desired information from the log message # You can also use the information passed out by the central repo if its available # %ae = Extract the user email from the last commit (author email) USER_EMAIL=$(git log -1 --format=format:%ae HEAD) # %an = Extract the username from the last commit (author name) USER_NAME=$(git log -1 --format=format:%an HEAD) # or use those values if you have them: # $USER, $GIT_AUTHOR_NAME, $GIT_AUTHOR_EMAIL if [ "$1" != refs/heads/master ] && [ CHECK_FOR_USER_NAME_OR_EMAIL ] { echo "ERROR: you are not allowed to update master" >&2 exit 1 } 个数字。我怎样才能做到这一点?如果需要任何澄清,请告诉我。非常感谢。

0 个答案:

没有答案