简体   繁体   中英

MongoDB Scala Driver counterpart to Javascript Object

I am trying to create a document with the counterpart to a 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.

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 .

For now, my workaround would be to serialize the Map[String, Any] and save it as 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? 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. If it is json, you can try to convert it to BSONDocument instead of Map with unknown format.

For example, see here case for converting play-json.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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