具有泛型的 ReactiveMongo:"ambiguous implicit values"

ReactiveMongo with generics: "ambiguous implicit values"

我不太确定这个错误是从哪里来的。我正在尝试从旧的 .find() 方法迁移,在该方法中我可以传递 Pattern: query: BSONDocument 来查找并调用 .one[T]。这工作得很好,但我想听从建议。

但是,我觉得我创建通用数据库访问对象的愿望正在引起一些头痛...请看下面。

我正在尝试读取的对象:

package Models

import reactivemongo.api.bson.{BSONDocumentHandler, Macros}

case class Person(name: String)

object Person {
  implicit val handler: BSONDocumentHandler[Person] = Macros.handler[Person]
}

包含我要执行的方法的 class(忽略 Await 等)

package Data

import reactivemongo.api.AsyncDriver
import reactivemongo.api.bson._
import reactivemongo.api.bson.collection.BSONCollection
import reactivemongo.api.commands.WriteResult

import scala.concurrent.{Await, Future}
import scala.concurrent.duration._
import scala.reflect.ClassTag

object DataService extends DataService

trait DataService {
  implicit val ec: scala.concurrent.ExecutionContext = scala.concurrent.ExecutionContext.global
  private val driver = new AsyncDriver
  private val connection = Await.result(driver.connect(List("localhost:32768")), 10.seconds)
  private val database = Await.result(connection.database("database"), 10.seconds)

  private def getCollection[T]()(implicit tag: ClassTag[T]): BSONCollection = database.collection(tag.runtimeClass.getSimpleName)

  def Get[T]()(implicit handler: BSONDocumentHandler[T], tag: ClassTag[T]): Future[Option[T]] = {
    val collection = getCollection[T]
    collection.find(BSONDocument("name" -> "hello"), Option.empty).one[T]
  }
}

我是如何尝试获取它的(忽略 Await,这仅用于测试目的):

val personName = Await.result(dataService.Get[Person](), 10.seconds).map(_.name).getOrElse("Not found")

我遇到的错误:

Error:(32, 19) ambiguous implicit values:
 both object BSONDocumentIdentity in trait BSONIdentityHandlers of type reactivemongo.api.bson.package.BSONDocumentIdentity.type
 and value handler of type reactivemongo.api.bson.BSONDocumentHandler[T]
 match expected type collection.pack.Writer[J]
   collection.find(BSONDocument("name" -> "hello"), Option.empty).cursor[T]

谢谢大家的帮助。

尝试在第二个参数查找方法中为您的选项添加类型,例如:

def Get[T]()(implicit handler: BSONDocumentHandler[T], tag: ClassTag[T]): Future[Option[T]] = {
  val collection = getCollection[T]
  collection.find(BSONDocument("name" -> "hello"), Option.empty[BSONDocument]).one[T]
}