1

我在 List[String] 中有一个产品 ID 列表。我想从 Mongo 返回一个 List[JsObject],为产品列表中的每个元素返回一个 JsObject。

我有以下内容可以只获得一种产品:

def getIndivProduct(productID: String): Future[List[JsObject]] = {

  val cursor: Cursor[JsObject] = collectionItems.
      find(Json.obj("product-number" -> productID)).
      cursor[JsObject]

  val futureProductList: Future[List[JsObject]] = cursor.collect[List]()

  futureProductList

}

如何“提供”要搜索和返回的字符串列表?有了这个签名:

 def getProductsFromList(productIDs: List[String]): Future[List[JsObject]] = {

    ???

 }

谢谢

4

2 回答 2

1

使用 $in,http://docs.mongodb.org/manual/reference/operator/query/in/

def getIndivProduct(productIDs: List[String]): Future[List[JsObject]] = {

  val cursor: Cursor[JsObject] = collectionItems.
      find(Json.obj("product-number" -> Json.obj("$in" -> productIDs))).
      cursor[JsObject]

  val futureProductList: Future[List[JsObject]] = cursor.collect[List]()
  futureProductList
}

我编写了简单的助手来编写复杂的查询,因为所有 Json -> Json -> Json 的东西真的很烦人。

https://github.com/sh1ng/ReactiveMongo-Queries

于 2014-10-03T07:29:27.463 回答
0

您需要一个从List-of-Future-of-ListFuture-of-List的转换功能

import scala.concurrent._
import ExecutionContext.Implicits.global

def singleFuture[A](futures: List[Future[List[A]]]): Future[List[A]] = {

    val p = Promise[List[A]]()
    p.success(List.empty[A])

    val f = p.future // a future containing empty list.

    futures.foldRight(f) {
        (fut, accum) =>  // foldRight means accumulator is on right.

        for {
            listAccum <- accum; 
            listA  <- fut  
        }
        yield (listA ::: listAccum)   // List[A] ::: List[A]
    }
}

鉴于此,它是直截了当的:

def getProductsFromList(productIDs: List[String]): Future[List[JsObject]] = {

    val indivProdList = productIDs.map(getIndivProduct(_))
    singleFuture(indivProdList)

}
于 2014-03-12T15:39:08.257 回答