Scala MongoDB 驱动程序的磁铁模式

Magnet pattern for Scala MongoDB driver

文档描述了使用磁铁模式来隐式转换为 BSON 类型。请参阅本页 http://mongodb.github.io/mongo-java-driver/4.1/driver-scala/bson/scala-documents/。我尝试定义一个扩展 BsonTransformer 的隐式对象,但它找不到该类型的编解码器。我错过了什么/有人让这个工作了吗?下面的示例代码,假设正在调用插入方法。

case class CustomType(specialString: String)

implicit object TransformCustomType extends BsonTransformer[CustomType] {

  def apply(value: CustomType): BsonString = 
      BsonString(value.specialString)
}

lazy val db: MongoDatabase = client.getDatabase(dbName).withCodecRegistry(DEFAULT_CODEC_REGISTRY)
lazy val testCollection: MongoCollection[CustomType] = db.getCollection[CustomType](collectionName)

def insert: Future[Completed] = testCollection.insertOne(CustomType("a")).toFuture

错误 - org.bson.codecs.configuration.CodecConfigurationException: 找不到 class com.bla.BlaClass$CustomType.

的编解码器

*请注意,我知道这可以通过

完成
val codecRegistry = fromRegistries(fromProviders(classOf[CustomType]))

但我只是用这个例子来要求学习更杂乱情况下的磁铁模式。

如果存在隐式 BsonTransformer[T]type class BsonTransformer) in a scope then there are implicit conversions

的实例
  • T => CanBeBsonValueCanBeBsonValueBsonValue 的包装),

  • (String, T) => CanBeBsonElementCanBeBsonElementBsonElement 的包装器,它是 StringBsonValue 的“元组”) ,

  • Iterable[(String, T)] => CanBeBsonElementsCanBeBsonElementsIterable[BsonElement] 的包装)

定义在 BsonMagnets (CanBeBsonValue, CanBeBsonElement, CanBeBsonElements are magnets 1 2).

然后Document可以通过工厂方法创建

def apply(elems: CanBeBsonElement*): Document

def apply(elem: CanBeBsonElements): Document

所以试试

val doc = Document("a" -> CustomType("bb"))

val testCollection: MongoCollection[Document] = ???

testCollection.insertOne(doc)