Mongodb 如何在Scala/ReactiveMongo中映射两个“未来”结果?
我有一个用Play和ReactiveMongo编写的应用程序,我想:Mongodb 如何在Scala/ReactiveMongo中映射两个“未来”结果?,mongodb,scala,future,reactivemongo,Mongodb,Scala,Future,Reactivemongo,我有一个用Play和ReactiveMongo编写的应用程序,我想: 在MongoDB中插入landingPage文档 插入新的登录页,并等待该页插入 计算新的landingPage文档总数并将其返回给用户 我有这个工作代码: // Insert the landing page and wait for it to be inserted, so we can then get the new count of landing pages. val futures = for { wr
- 在MongoDB中插入
文档landingPage
- 插入新的登录页,并等待该页插入
- 计算新的landingPage文档总数并将其返回给用户
// Insert the landing page and wait for it to be inserted, so we can then get the new count of landing pages.
val futures = for {
wr <- landingPagesCollection.insert(landingPage)
count <- landingPagesCollection.count()
} yield count
futures.map { (count: Int) =>
Created(Json.obj(
"created" -> true,
"landingPage" -> landingPage.toJson,
"count" -> count
))
}
我收到以下错误消息:
任何人都可以解释如何在地图功能中访问wr
?尝试更改
futures.map { (wr: WriteResult, count: Int) =>
致:
或者只是:
futures.map { case (wr, count) =>
希望这有助于如果函数采用2个参数,而不是元组,则所使用的语法可以正常工作
list.map((a: Int, b: String) => ...)
如果需要元组,可以执行以下操作:
list.map(tuple: (Int, String) => {
val (num, str) = tuple
...
})
或者按照公认答案中的建议传递部分函数。它将匹配参数(匹配元组),并允许您稍后使用提取的值
list.map { case (a: Int, b: String) => ... }
请注意,在这种情况下,需要大括号
类型注释可以被删除,因为它们可以被编译器推断。添加
case
使其工作!谢谢你能解释一下为什么这个案子能成功吗?我以为case是用于match
块中的。@AmyB“一个匿名函数可以由一系列case定义”§8.5
list.map(tuple: (Int, String) => {
val (num, str) = tuple
...
})
list.map { case (a: Int, b: String) => ... }