Mongodb 在Play Framework 2中使用Reactivemongo读取整个集合的奇怪行为2

Mongodb 在Play Framework 2中使用Reactivemongo读取整个集合的奇怪行为2,mongodb,scala,playframework-2.0,reactivemongo,Mongodb,Scala,Playframework 2.0,Reactivemongo,我有以下代码: def all: String = { val query = BSONDocument("name" -> BSONDocument("$ne" -> "allDocs")) val cursor = carsCollection.find(query).cursor[BSONDocument] Logger.debug("Before cursor") cursor.enumerate.apply(Iteratee.fore

我有以下代码:

  def all: String = {

    val query = BSONDocument("name" -> BSONDocument("$ne" -> "allDocs"))

    val cursor = carsCollection.find(query).cursor[BSONDocument]
    Logger.debug("Before cursor")
    cursor.enumerate.apply(Iteratee.foreach {
      doc =>
        Logger.debug("found document: " + doc.getAs[BSONString]("name").get.value)
        //Logger.debug("found document: " + doc.getAs[BSONString]("area").get.value)
    })
    "Ok"
  }
当我运行此代码时,播放控制台显示来自
mongodb
的12个不同文档的
字段“name”
。当我取消注释第二个记录器调用时,系统只打印一个名称,然后停止。数据库中存在字段
“area”
,没有问题


我做错什么了吗?

我猜
doc.getAs[BSONString](“区域”).get.value
引发了一些异常

您应该测试是否存在值以及值的类型,以确保:

cursor.enumerate.apply(Iteratee.foreach { doc =>
  // ...
  doc.getAs[BSONString]("area") match {
    case Some(BSONString(area)) => Logger.debug(s"area is BSONString of value = $area")
    case None => Logger.debug("area does not exist or is not a BSONString"
  }
}
getAs[BSONString]
方法返回一个
选项[BSONString]
。如果存在一个值,但无法将该值解析为
BSONString
——换句话说,当该值不是BSONString而是BSONInteger、BSONLong、BSONDocument等时,则返回
None
。由于您在其上调用了
get
,而没有检查该选项是否已定义,因此它可能会抛出
NoTouchElementException

另一种方法是:

cursor.enumerate.apply(Iteratee.foreach { doc =>
  // ...
  doc.get("area") match {
    case Some(BSONString(area)) => Logger.debug(s"area is a BSONString of value = $area")
    case Some(otherBSONValue) => Logger.debug(s"area exists but is not a BSONString: $otherBSONValue")
    case None => Logger.debug("area does not exist or is not a BSONString"
  }
}
如果迭代对象中存在异常,那么最终的结果可能是错误的

val future = cursor.enumerate |>>> Iteratee.foreach { doc =>
  Logger.debug("found document: " + doc.getAs[BSONString]("name").get.value)
  Logger.debug("found document: " + doc.getAs[BSONString]("area").get.value)
}
future.onComplete {
  case Success(_) => Logger.debug("successful!")
  case Failure(e) => Logger.debug(s"there was an exception! ${e.getMessage}")
}

没有错误?你确定你的区域字段总是满的吗?你完全正确。我粘贴的代码只是一个测试,但问题是数据类型。当然这个区域不是弦,它是一个双环。谢谢你的帮助!