0

我有一个播放控制器操作,它使用 ReactiveMongo 在 MongoDB 中编辑文档。代码如下所示。名称和关键字都是可选的。我正在创建一个临时BSONDocument()文件并根据名称和关键字是否存在向其中添加元组不为空。但是,tmp当前是可变的(是 a var)。我想知道如何才能摆脱var.

    def editEntity(id: String, name: Option[String], keywords: Option[String]) = Action          {

    val objectId = new BSONObjectID(id)

    //TODO get rid of var here
    var tmp = BSONDocument()

    if (name.exists(_.trim.nonEmpty)) {
      tmp = tmp.add(("name" -> BSONString(name.get)))
    }

    val typedKeywords : Option[List[String]] = Utils.getKeywords(keywords)
    if (typedKeywords.exists(_.size > 0)) {
      tmp = tmp.add(("keywords" -> typedKeywords.get.map(x => BSONString(x))))
    }

    val modifier = BSONDocument("$set" -> tmp)
    val updateFuture = collection.update(BSONDocument("_id" -> objectId), modifier)
}

更新在查看@Vikas 的解决方案后,我想到如果Option我需要处理更多(比如 10 或 15)个 input 怎么办。也许基于foldorreduce的解决方案会更好地扩展?

4

1 回答 1

1

BSONDocument()如果这些if条件都不匹配,则在您当前的代码中添加一个空?val modifier = BSONDocument("$set" -> tmp)将有一个空的tmpif namewasNonetypedKeyWordswas None。假设这就是您想要的,这是摆脱瞬态的一种方法var。还要注意在var本地(在方法中)并不是一件坏事(当然我仍然会让代码看起来更漂亮一些)

 val typedKeywords : Option[List[String]] = Utils.getKeywords(keywords)
 val bsonDoc = (name,typedKeywords)  match{
  case (Some(n),Some(kw) ) => BSONDocument().add( "name" -> BSONString(n)) .add(("keywords" -> kw.map(x => BSONString(x))))
  case (Some(n), None) => BSONDocument().add( "name" -> BSONString(n))
  case (None,Some(kw)) => BSONDocument().add(("keywords" -> kw.map(x => BSONString(x))))
  case (None,None) => BSONDocument()

}
val modifier = BSONDocument("$set" -> bsonDoc)
于 2014-06-06T23:11:17.243 回答