简体   繁体   中英

MongoDB Scala Driver doesn't allow use Map collection in case class

I just started using MongoDB and I'm trying to write a small application to test Mongo with Scala. I created the following case class in order to cast the Documents to a Scala class:

case class User(
                 _id: ObjectId,
                 userId: String,
                 items: Map[String, Int]
               )

object User {
  def apply(userId: String , items: Map[String, Int]): User =
    new User(new ObjectId, userId, items)

  implicit val codecRegistry: CodecRegistry = 
    fromRegistries(fromProviders(classOf[User]), DEFAULT_CODEC_REGISTRY)
}

I get the following error but I don't know why since the Map keys are in fact strings.

[ERROR] error: Maps must contain string types for keys
[INFO]   implicit val codecRegistry: CodecRegistry = fromRegistries (fromProviders (classOf [User]), DEFAULT_CODEC_REGISTRY)
[INFO]                                                                                      ^
[ERROR] one error found

I'm also applying the codecRegistry to the MongoDatabase.

Thank you very much.

The problem was that I was using a version of the driver that is compiled for Scala 2.11 and not 2.12. By changing the Maven dependency from

<dependency>
   <groupId>org.mongodb.scala</groupId>
   <artifactId>mongo-scala-driver_2.11</artifactId>
   <version>2.2.1</version>
</dependency>

to

<dependency>
   <groupId>org.mongodb.scala</groupId>
   <artifactId>mongo-scala-driver_2.12</artifactId>
   <version>2.2.1</version>
</dependency>

solved the problem.

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