简体   繁体   English

Play2 Scala模型-合并对象

[英]Play2 Scala models - merge objects

I'm using Play2+Scala+ReactiveMongo to build a web application. 我正在使用Play2 + Scala + ReactiveMongo来构建Web应用程序。 Since mongodb doesn't require all documents to have the same structure, I make a large use of case classes with Options as parameters to implement models. 由于mongodb并不需要所有文档都具有相同的结构,因此我大量使用带有Options作为参数的案例类来实现模型。 For example: 例如:

case class PersonInfo(address: Option[String],
                      telephone: Option[String],
                      age: Option[Int],
                      job: Option[String])
case class Person(id: UUID, name: String, info: PersonInfo)

Now suppose I want to merge two PersonInfo objects, for example in a update function. 现在假设我想合并两个PersonInfo对象,例如在update函数中。 I do right now is: 我现在做的是:

val updPInfo = old.copy(address = new.address orElse address,
                        telephone = new.telephone orElse telephone,
                        age = new.age orElse age,
                        job = new.job orElse job)

This way I have an object that has new values where they were specified by the new object and old values for the remaining ones. 这样,我有一个对象,该对象具有新值(由new对象指定)和旧值(其余值为旧值)。

This actually works fine, but it is bit ugly to see when the list of parameters grows. 这实际上可以正常工作,但要看参数列表何时增长却很难看。

Is there a more elegant way to do that? 有没有更优雅的方法可以做到这一点?

If the only place you need this is in mongo, you can do it, like this: 如果您唯一需要的地方是在mongo,则可以这样做,如下所示:

collection.
      update(
          Json.obj("_id" -> id),
          Json.obj("$set" -> Json.toJson(new))
      )

That way you'll have correct presentation in DB, which you can read and use afterwards. 这样,您将在DB中拥有正确的演示文稿,之后可以阅读和使用。

or 要么

If you need it in Scala, you can merge 2 Json presentations: 如果在Scala中需要它,则可以合并2个Json演示文稿:

val merged = Json.toJson(old).deepMerge(new).as[PersonInfo]

Which is not quite better, then what you are doing now. 那还不怎么样,那么您现在在做什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM