【问题标题】:Inserting an object into Mongo database using Scala's ReactiveMongo driver使用 Scala 的 ReactiveMongo 驱动程序将对象插入 Mongo 数据库
【发布时间】:2016-10-03 22:02:44
【问题描述】:

我正在学习如何同时使用 Scala、MongoDB 和 Play 框架,并且我一直在查看位于此处的演示项目:https://github.com/jonasanso/play-reactive-mongo-db

但是,我不明白create() 方法中的语法。有没有不使用关键字yield 的另一种写法?我还在学习 Scala,我不明白这种方法是如何工作的。

  def create(name: String, population: Int) = Action.async {
    for {
      cities <- citiesFuture
      lastError <- cities.insert(City(name, population))
    } yield
      Ok("Mongo LastError: %s".format(lastError))
  }

【问题讨论】:

标签: mongodb scala playframework play-reactivemongo


【解决方案1】:

如果你不想使用 for-yield 语法,你可以将你的代码翻译成等价的:

citiesFuture
  .flatMap (cities => cities.insert(City(name, population))
  .map (lastError => Ok(s"Mongo LastError: $lastError"))

【讨论】:

  • 好的,谢谢!我想知道我可以用map() 替换flatMap() 还是有特定的理由使用flatMap()?我仍然在理解何时使用其中一个而不是另一个。
  • 你不能在这里使用 map 而不是 flatMap,因为在这种情况下你会得到 Future[Future[String]]。要制作期货链:首先执行 cityFuture,然后执行 future.insert(...) 你必须使用 flatMap。最后对于 city.insert 的结果,您可以使用 map 将字符串结果转换为 Play 的“Ok”
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-04-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多