2013-07-13 28 views
0

我有以下代碼:古怪的行爲在遊戲框架閱讀使用Reactivemongo整個集合2

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"。當我取消註釋第二個Logger調用時,系統僅打印一個名稱並停止。字段"area"存在於db中,沒有問題。

我做錯了什麼?

+0

沒有錯誤?你確定你的區域總是被填滿嗎? –

回答

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]。如果有值,但這個值不能被解析爲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異常,最終的未來可能是錯誤的。

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}") 
} 
+0

你是完全正確的。我粘貼的代碼只是一個測試,但問題是數據類型。當然,這個區域不是字符串,它是一個BSONDouble。謝謝你的幫助! –