Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Scala和ReactiveMongo中基于Play 2控制器中的输入值在功能上构建文档_Scala_Functional Programming_Playframework 2.0_Reactivemongo - Fatal编程技术网

在Scala和ReactiveMongo中基于Play 2控制器中的输入值在功能上构建文档

在Scala和ReactiveMongo中基于Play 2控制器中的输入值在功能上构建文档,scala,functional-programming,playframework-2.0,reactivemongo,Scala,Functional Programming,Playframework 2.0,Reactivemongo,我有一个Play controller操作,它使用ReactiveMongo在MongoDB中编辑文档。代码如下所示。名称和关键字都是可选的。我正在创建一个tempBSONDocument(),并根据名称和关键字是否为空向其中添加元组。但是,tmp当前是可变的(是一个var)。我想知道如何摆脱var def editEntity(id: String, name: Option[String], keywords: Option[String]) = Action {

我有一个Play controller操作,它使用ReactiveMongo在MongoDB中编辑文档。代码如下所示。名称和关键字都是可选的。我正在创建一个temp
BSONDocument()
,并根据名称和关键字是否为空向其中添加元组。但是,
tmp
当前是可变的(是一个
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的解决方案后,我想到如果有更多(比如10或15)个输入
选项
我需要处理。也许基于
折叠
减少
的解决方案可以更好地扩展

在当前代码中,如果这些
条件都不匹配,则添加一个空的
BSONDocument()
<如果
name
was
None
typedKeyWords
was
None
,则code>val修饰符=BSONDocument($set->tmp)
将有一个空的
tmp
。假设这就是您想要的,这里有一种方法可以消除瞬态
var
。还要注意的是,在本地(在方法中)使用
var
并不是一件坏事(当然,我仍然会使代码看起来更漂亮)


你的解决方案会奏效,肯定比我最初的解决方案要好。您是正确的,如果没有任何更改,则无需编辑文档。我可以回来。我想知道模式匹配是否可以扩展到10个参数?也许是一份B文件上的折页?
 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)