0

我正在将代码从 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) {
  // ...
}

我只是不喜欢那个样子。我该如何改进它?

4

1 回答 1

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。我没有测试代码,它几乎是一个伪代码。

问候。

于 2015-12-04T20:17:58.423 回答