简体   繁体   English

如何将使用mongodb-scala-driver检索的Scala值绑定到标识符?

[英]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.

相关问题 Slick / Scala:什么是Rep [Bind],如何将其变成值? - Slick/Scala: What is a Rep[Bind] and how do I turn it into a value? 我该如何使用scala的casbah驱动程序编写mongodb查询,该驱动程序使用子字符串并检查该字段是否在提供的值列表中? - How do I write a query for mongodb using the casbah driver for scala that uses a substring and checks if the field is in a list of supplied values? 如何将MongoDB Scala异步驱动程序与Akka Streams集成? - How can I integrate MongoDB Scala Async driver with Akka Streams? 如何使用 MongoDB Scala 驱动程序将聚合结果累积到集合中 - How to accumulate aggregation results into a collection using MongoDB Scala Driver MongoDB Scala异步驱动程序 - MongoDB Scala Async Driver Scala mongodb驱动程序 - Scala mongodb driver 如何使用 MongoDb Scala 驱动程序进行同步查询 - How to make synchronous queries using MongoDb Scala driver 如何使用属性值在 Scala 中声明 KafkaListener 的主题 - How do I declare the topic of a KafkaListener in Scala using a property value 如何使用Scala反射获取符号的值? - How do I get the value of a symbol using Scala reflection? foo:{$ gt:“ A”,$ lt:“ Z”}; 如何在scala驱动程序中编写此代码? - foo: { $gt: “A”, $lt: “Z”}; How do I write this in the scala driver?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM