[英]How do I bind a Scala value retrieved using mongodb-scala-driver to an identifier?
I'm converting code from Casbah to mongodb-scala-driver, and when it comes to capturing the result of a query, the best I've come up with so far is: 我正在将代码从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) {
// ...
}
I just don't like the look of that. 我只是不喜欢那种外观。 How can I improve it? 我该如何改善?
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)
Or 要么
def doSome(doc:Document):Unit = {
//do something here with 'doc'
}
collection.find(and(equal("name",name),equal("hobby",
hobby))).first().subscribe(doSome)
You need to think asynchronously, something like javascript with its callbacks. 您需要异步思考,类似于带有回调的javascript。
PS. PS。 I did not test the code, it is almost a pseudocode. 我没有测试代码,它几乎是伪代码。
regards. 问候。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.