Question

I'm new with ReactiveMongo and I want to create a custom document reader/writer for one object but I'm getting this error

type mismatch;  found   :
reactivemongo.bson.BSONDocumentReader[reactivemongo.bson.BSONDocument]
required:
reactivemongo.bson.BSONDocumentReader[db.DataBase.Estudiante]  Note:
implicit object EstudianteReader is not applicable here because it
comes after the application point and it lacks an explicit result type
Error occurred in an application involving default arguments.

This is my code and is based in this example I found in reactivemongo's official webpage.

package db

import scala.concurrent.ExecutionContext.Implicits.global

import reactivemongo.api._
import reactivemongo.bson._

object DataBase {

  //Driver para la conexion
  val driver = new MongoDriver

  //Conexion con mongoDB
  val connection = driver.connection(List("localhost"))

  //Conexion con la base de datos AMDB
  val db = connection("reactive")

  //Colección domainNames que se encuentra en la base de datos AMDB
  val collection = db("estudiantes")

  def findAllDomainNames() = {

    val query = BSONDocument()
    collection.find(query).cursor[Estudiante]
    //.cursor[BSONDocument].collect[List]()
  }

case class Estudiante(id: Option[BSONObjectID], nombre: String, apellidos: String, edad: Int)

  object Estudiante {

    implicit object EstudianteWriter extends BSONDocumentWriter[Estudiante] {
      def write(estudiante: Estudiante): BSONDocument = {
        BSONDocument(
          "_id" -> estudiante.id.getOrElse(BSONObjectID.generate),
          "nombre" -> estudiante.nombre,
          "appellidos" -> estudiante.apellidos,
          "edad" -> estudiante.edad.toString)
      }
    }

    implicit object EstudianteReader extends BSONDocumentReader[Estudiante] {
      def read(doc: BSONDocument): Estudiante = {
        Estudiante(
          doc.getAs[BSONObjectID]("_id"),
          doc.getAs[String]("nombre").get,
          doc.getAs[String]("appellidos").get,
          doc.getAs[Int]("edad").get)
      }
    }

  }

  def main(args: Array[String]) {
    println(findAllDomainNames);
  }
}

What is missing/wrong?

Thank you all in advance!

Was it helpful?

Solution

Move the declaration of the object Estudiante above DataBase and add an import in the scope of DataBase:

import Estudiante._
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top