无法使用flatmap调用BSONCollection.findAndRemove()

时间:2019-02-12 12:37:49

标签: scala reactivemongo

ReactiveMongo集合类型提供方法findAndRemove,该方法可用于根据查询条件从集合中删除一个文档。它返回一个删除操作的描述结果的Future。在此Future的Future上调用flatMap()会产生一个相当隐秘的错误消息:

type mismatch;
 found   : reactivemongo.api.collections.bson.BSONCollection => scala.concurrent.Future[x$5.BatchCommands.FindAndModifyCommand.FindAndModifyResult] forSome { val x$5: reactivemongo.api.collections.bson.BSONCollection }
 required: reactivemongo.api.collections.bson.BSONCollection => scala.concurrent.Future[S]

我猜这是内部类的结果类型,我不能直接使用它。我不明白我应该在这里做什么才能使用它。整个清单为:

import reactivemongo.api.collections.bson.BSONCollection
import reactivemongo.api.{Cursor, DB, MongoConnection, MongoDriver}
import reactivemongo.bson.{BSONDocument, BSONDocumentReader, BSONDocumentWriter, Macros}

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.{Await, Future}
import scala.concurrent.duration._

object ReactiveMongoTest extends App {

  case class Element(symbol: String, atomicNumber: Long, atomicMass: Double)
  implicit val elementReader: BSONDocumentReader[Element] = Macros.reader[Element]
  implicit val elementWriter: BSONDocumentWriter[Element] = Macros.writer[Element]

  val elements = Seq(
    Element("Fe", 26, 55.845),
    Element("Co", 27, 58.933),
    Element("Ni", 28, 58.693)
  )

  def await[T](future: => Future[T]): T = Await.result(future, Duration.Inf)


  lazy val driver: MongoDriver = MongoDriver()
  lazy val conn: MongoConnection = driver.connection(Seq("localhost"))
  def testDb: Future[DB] = conn.database("testDb")
  def testColl: Future[BSONCollection] = testDb.map(_.collection("testColl"))

  def insert = testColl.flatMap(_.insert(ordered = true).many(elements))

  def list = testColl.flatMap {
    _.find(BSONDocument(), projection = Option.empty)
      .cursor[Element]()
      .collect[Seq](Int.MaxValue, Cursor.FailOnError[Seq[Element]]())
  }

  def remove = testColl.flatMap(_.findAndRemove(BSONDocument("atomicNumber" -> 26)))

  println(await(insert))

  await(list).foreach(x => println(s"listing -> ${x}"))

//  println(await(remove))

  println("After removing!")
  await(list).foreach(x => println(s"listing -> ${x}"))

  sys.exit()

}

错误消息是:

Error:(37, 48) type mismatch;
 found   : reactivemongo.api.collections.bson.BSONCollection => scala.concurrent.Future[x$4.BatchCommands.FindAndModifyCommand.FindAndModifyResult] forSome { val x$4: reactivemongo.api.collections.bson.BSONCollection }
 required: reactivemongo.api.collections.bson.BSONCollection => scala.concurrent.Future[S]
  def remove = testColl.flatMap(_.findAndRemove(BSONDocument("atomicNumber" -> 26)))

更新1: 调用地图即可:

def remove = testColl.map(_.findAndRemove(BSONDocument("atomicNumber" -> 26)))
println(await(await(remove)))

1 个答案:

答案 0 :(得分:4)

ReactiveMongo对于许多此类内部案例类太聪明了,每次我不得不使用它时,都会遇到类似这样的怪异问题。您可以通过提供类型注释来固定它的存在范围,以强制其进行编译:

scala> type FAMResult =
     |   c.BatchCommands.FindAndModifyCommand.FindAndModifyResult forSome {
     |     val c: BSONCollection
     |   }
defined type alias FAMResult

scala> def remove =
     |   testColl.flatMap[FAMResult](_.findAndRemove(BSONDocument("atomicNumber" -> 26)))
remove: scala.concurrent.Future[FAMResult]

但是,除非您不在乎删除命令的结果,否则这可能不是理想的选择。更好的方法是将Future[<blah blah blah>.FindAndModifyResult]映射到flatMap内部 ,以便最终获得更有用的类型:

scala> def remove = testColl.flatMap(
     |   _.findAndRemove(BSONDocument("atomicNumber" -> 26)).map(_.value)
     | )
remove: scala.concurrent.Future[Option[reactivemongo.bson.BSONDocument]]

如果您实际上不关心结果,也可以.map(_ => ()),如果您想要对结果进行解码,则可以.map(_.result[Element]),等等。