我有一个播放控制器操作,它使用 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 怎么办。也许基于fold
orreduce
的解决方案会更好地扩展?