问题描述
文档介绍了如何使用磁铁模式将隐式转换为BSON类型。参见此页面http://mongodb.github.io/mongo-java-driver/4.1/driver-scala/bson/scala-documents/。我尝试定义一个扩展BsonTransformer的隐式对象,但找不到该类型的编解码器。我是否缺少某些东西/有人在工作吗?下面的示例代码假定正在调用insert方法。
use Gedmo\Timestampable\Traits\TimestampableEntity;
class Article
{
use TimestampableEntity;
}
错误- org.bson.codecs.configuration.CodecConfigurationException:找不到类com.bla.BlaClass $ CustomType的编解码器。
*请注意,我知道这可以通过
完成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
但是我只是用这个例子来要求学习一个更复杂情况下的磁铁图案。
解决方法
如果范围中存在隐式BsonTransformer[T]
(实例为type class BsonTransformer
),则存在implicit conversions
-
T => CanBeBsonValue
(CanBeBsonValue
是BsonValue
的包装), -
(String,T) => CanBeBsonElement
(CanBeBsonElement
是BsonElement
的包装,String
是BsonValue
和Iterable[(String,T)] => CanBeBsonElements
的“元组”), -
CanBeBsonElements
(Iterable[BsonElement]
是CanBeBsonValue
的包装)
BsonMagnets
中定义的(CanBeBsonElement
,CanBeBsonElements
,def apply(elems: CanBeBsonElement*): Document
def apply(elem: CanBeBsonElements): Document
是磁体1 2)。
然后可以通过工厂方法创建Document
val doc = Document("a" -> CustomType("bb"))
val testCollection: MongoCollection[Document] = ???
testCollection.insertOne(doc)
所以尝试
let queryResults = returnedQueryData // data returned from SQL query
let jsonarray = {}
for (row in queryResults) {
jsonarray[row.id] = {
id: row['id'],username: row['username'],email: row['email']
}