Mongodb Document to Scala case class

前端 未结 2 1644

I am using MongoDB scala driver. I have a problem with fetching record from MongoDB. Following is my MongoDB initialization

private val client: MongoClient          


        
2条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-14 21:42

    You could use a JSON library.

    In play-json

    case class WorkOrder (
      id: String,
      workOrderId: String,
      thingId: String,
      alertId: String,
      description: String,
      lastViewedDate: Date,
      suggestedMaintenanceDate: Date,
      startDate: Date
    )
    
    object WorkOrder {
      implicit lazy val fmt = Json.format[WorkOrder]
    }
    
    def documentToWorkOrder(doc: Document): WorkOrder = {
      Json.parse(user.toJson().toString).validate[WorkOrder] match {
        case JsSuccess(_, workOrderObj) => workOrderObj
        case JsError(throwable)  => throw throwable
      }
    }
    
    //then in your code
    MongoFactory.WorkOrdercollection.find(query).subscribe(
     (user: Document) => documentToWorkOrder(user),
     (error: Throwable) => println(s"Query failed: ${error.getMessage}"),
     () => println("Done")
    )
    

提交回复
热议问题