0

次のコードがあります。

  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"
  }

このコードを実行すると、play コンソールに"name".NET からの 12 の異なるドキュメントのフィールドが表示されmongodbます。2 番目の Logger 呼び出しのコメントを外すと、システムは名前を 1 つだけ表示して停止します。フィールド"area"は問題なくデータベースに存在します。

私は何か間違ったことをしていますか?

4

1 に答える 1

1

私の推測では、doc.getAs[BSONString]("area").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]メソッドは を返しますOption[BSONString]。値はあるが、この値を a として解析できなかったBSONString場合、つまり、値が BSONString ではなく、BSONInteger、BSONLong、BSONDocument などである場合、Noneが返されます。getオプションが定義されているかどうかを確認せずに呼び出すため、 NoSuchElementException.

これを行う別の方法:

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"
  }
}

iteratee に例外がある場合、最終的な future がエラーになる可能性があります。

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}")
}
于 2013-07-15T12:51:40.873 に答える