2016-09-08 98 views
1
def find(query: Document, projection: Document, collectionName : MongoCollection[Document]) : Document = { 
      var previousDoc : Document = Document() 
/*var future = collectionName.find(query).projection(projection).toFuture()*/ 
        try { 
collectionName.find(query).projection(projection).subscribe(
           (data: Document) => previousDoc = data, 
           (error: Throwable) => println("error"), 
           () => println("Completed") 
           ) 
        } catch { 
        case x:Exception => throw new MongoCustomException(x) 
        } 
    //Await.result(future, Duration.Inf) 
Thread.sleep(1000) 
    previousDoc 
    } 

这是我的代码片段,如果我没有使用等待或线程,我会得到空文档。在从mongodb获取数据之前它正在退出。我想在Scala中同步运行此过程,而不使用Await和Thread方法。我想使用scala驱动程序在mongodb上执行查找操作

+0

你正在使用哪一个mongo客户端? – Abhi

+0

你可以在你从查询中获得的'Observable'上调用'toFuture',然后对它进行模式匹配以得到值。 – sebszyller

+0

您可以查看http://reactivemongo.org/releases/0.11/documentation/tutorial/find-documents.html – cchantep

回答

0

不要使用var从observable中获取值。你的程序在未来完成之前停止并且可变变量没有来自Mongo的任何值。如果你想要这个值你的程序退出你的线程必须Await.result(R,10秒)前等待转换到可观察未来

val r = collectionName.find(query).projection(projection).toFuture 

。在你的情况下,你的代码在一个线程中执行的函数中,而“previousDoc = data”不会阻塞它,因此它只是返回。改变返回类型为未来[序号[文献]

def find(query: Document, projection: Document, collectionName : MongoCollection[Document]) : Future[Seq[Document]] = { 
collectionName.find(query).projection(projection).toFuture()      
} 

的Scala蒙戈驱动工作在使用观测量或期货异步方式。所以试着以这种方式工作。

相关问题