Search code examples
jsonmongodbscalajson4sobjectid

ObjectIds don't get retrieved from collection (Scala + MongoDB)


There is a MongoDB instance on my computer with a database. A couple of documents are present in one of the collections, I inserted them manually. There is a Scala application to manipulate the database. There is a case class called Location.

case class Location(_id: Option[ObjectId] = None, name: String) {
  var visible: Boolean = false
}

This is the MongoDB configuration in the application.

private val customCodecs = fromProviders(
  classOf[Location]
)
private val javaCodecs =
    fromCodecs(new LocalDateTimeDateCodec(), new LocalDateDateCodec())

private val codecRegistry =
  fromRegistries(customCodecs, javaCodecs, 
  DEFAULT_CODEC_REGISTRY)
val dbConnection = MongoClient(dbURI)

val database: MongoDatabase = dbConnection.getDatabase(dbName).withCodecRegistry(codecRegistry)

There are more classOf definitions in the customCodecs, just removed them. The dbURI string is retrieved from a config file. There is a controller endpoint, which returns all Locations from the database. The result is this:

[{"_id":{},"name":"Hungary","visible":false},{"_id":{},"name":"Germany","visible":false},{"_id":{},"name":"France","visible":false},{"_id":{},"name":"Switzerland","visible":false},{"_id":{},"name":"Poland","visible":false}]

The documents in the database have ObjectId, since I entered them manually, and some documents should have the visibility property true. I suspect there is something wrong with the JSON serialization, but cannot figure it out what. This is the code which queries the collection.

val query = collection.find().toFuture()
Await.result(query, 10.seconds).toList

The service method calls this code and passes the result to the controller.

import org.json4s.native.Serialization.write
val languages = enrollmentService.getAllLanguages
    logger.info("GET all languages")
    Ok(Json.parse(write[List[Language]](languages)))

I use json4s for JSON serialization / deserialization.

What could be the issue here?


Solution

  • Perhaps you need to include org.json4s.mongo.ObjectIdSerializer?