简体   繁体   English

MongoDB Scala驱动程序与Javascript对象对应

[英]MongoDB Scala Driver counterpart to Javascript Object

I am trying to create a document with the counterpart to a Javascript Object Map[String, Any] . 我正在尝试创建与Javascript Object Map[String, Any]对应的文档。 When I try to insert a new Document I'll get this Exception: 当我尝试插入新文档时,将出现以下异常:

org.bson.codecs.configuration.CodecConfigurationException: Can't find a codec for class java.lang.Object. org.bson.codecs.configuration.CodecConfigurationException:找不到类java.lang.Object的编解码器。

This is my test document description: 这是我的测试文档说明:

import org.mongodb.scala.bson.ObjectId

object ExampleCollection {
  def apply(test: Map[String, Any]): ExampleCollection = new ExampleCollection(new ObjectId(), test)
}

case class ExampleCollection(_id: ObjectId, test: Map[String, Any])

This is the Codec Registry: 这是编解码器注册表:

val codecRegistry = fromRegistries(fromProviders(classOf[ExampleCollection]), DEFAULT_CODEC_REGISTRY)

I have written a small Application and pushed it on github . 我编写了一个小应用程序,并将其推到github上

For now, my workaround would be to serialize the Map[String, Any] and save it as String. 现在,我的解决方法是序列化Map[String, Any]并将其另存为String。

So, my question would be, what do I have to do to use Map[String, Any] as a type for my dynamic object in mongodb? 因此,我的问题是,在mongodb中将Map[String, Any]用作动态对象的类型该怎么办? Or can I do something else to get it working? 还是我可以做些其他的事情来使其正常工作?

You cannot pass just Any to mongo, as soon as it does not know what it is and how to serialize/deserialize it. 一旦它不知道它是什么以及如何对其进行序列化/反序列化,您就不能仅将它传递给mongo。 If it is json, you can try to convert it to BSONDocument instead of Map with unknown format. 如果是json,则可以尝试将其转换为BSONDocument而不是格式未知的Map

For example, see here case for converting play-json. 例如,请参阅此处转换play-json的案例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM