我正在将代码从Casbah转换为mongodb-scala-driver,当涉及到捕获查询结果时,到目前为止我提出的最好的是:
var doc: Option[Document] = None
collection.find(and(equal("name",name),equal("hobby", hobby))).first().subscribe(
(result: Document) => doc = Some(result)
)
if (doc.isDefined) {
// ...
}
我只是不喜欢那种样子。我该如何改进呢?
答案 0 :(得分:1)
val observer = new Observer[Document] {
override def onComplete {
//do something when completed
}
override def onError(e: Throwable) {
//do something when error
}
override def onNext(doc: Document) {
//do some when a record is found
// and keep your logic here maybe call another function passing 'doc'
}
}
collection.find(and(equal("name",name),equal("hobby",
hobby))).first().subscribe(observer)
或者
def doSome(doc:Document):Unit = {
//do something here with 'doc'
}
collection.find(and(equal("name",name),equal("hobby",
hobby))).first().subscribe(doSome)
你需要异步思考,比如javascript及其回调。
PS。我没有测试代码,它几乎是一个伪代码。
问候。