0
我只是學習Scala和相關技術的新手。我遇到了LoadUser應該返回一條記錄但將來空的問題。ReactiveMongo查詢返回無
我收到以下錯誤: java.util.NoSuchElementException:None.get
我明白這是不理想的Scala,所以隨時提出改進我。
class MongoDataAccess extends Actor {
val message = "Hello message"
override def receive: Receive = {
case data: Payload => {
val user: Future[Option[User]] = MongoDataAccess.loadUser(data.deviceId)
val twillioApiAccess = context.actorOf(Props[TwillioApiAccess], "TwillioApiAccess")
user onComplete {
case Failure(exception) => println(exception)
case p: Try[Option[User]] => p match {
case Failure(exception) => println(exception)
case u: Try[Option[User]] => twillioApiAccess ! Action(data, u.get.get.phoneNumber, message)
}
}
}
case _ => println("received unknown message")
}
}
object MongoDataAccess extends MongoDataApi {
def connect(): Future[DefaultDB] = {
// gets an instance of the driver
val driver = new MongoDriver
val connection = driver.connection(List("192.168.99.100:32768"))
// Gets a reference to the database "sensor"
connection.database("sensor")
}
def props = Props(new MongoDataAccess)
def loadUser(deviceId: UUID): Future[Option[User]] = {
println(s"Loading user from the database with device id: $deviceId")
val query = BSONDocument("deviceId" -> deviceId.toString)
// By default, you get a Future[BSONCollection].
val collection: Future[BSONCollection] = connect().map(_.collection("profile"))
collection flatMap { x => x.find(query).one[User] }
}
}
感謝
這將需要的功能從未來簽名[選項[用戶]到未來[用戶]這是欺騙的調用代碼,因爲它可能會,也可能不會得到用戶一旦未來已經完成。無論如何,您建議的更改仍然返回無。 –
如果返回'Future(Option.empty [T])',則表示沒有匹配的文檔。 – cchantep
MongoDB query db.getCollection('profile')。find({「deviceId」:「03af30d0-4dc6-11e6-beb8-9e71128cae77」})返回正確的文檔。 –