我正在进入我的API中的一些case类,如下所示:
case class UserUpdate(
name: Option[String],
age: Option[String],
city: Option[String])
从这个case类中,我需要为mongo构建更新json,如下所示:
{"basicInfo.name": "new nameeee","age.vatId": "23"}
因为所有字段都是可选的,所以我需要遍历这些字段,并通过定义的字段来构建它。
所以我这样做了:
val updateAsMap = Json.toJson(userUpdateObj).as[JsObject]
.fields.map(fieldTpl => fieldTpl.copy(_1 = s"basicInfo.${fieldTpl._1}")).toMap
val userUpdateJson = Json.toJson(updateAsMap)
val query = json("userId" -> userId)
val update = json("$set" -> userUpdateJson)
有没有更好的建议,一些看起来更优雅的建议?