2

I'm trying to use reactivemongo getstarted to investigate how to use it. I use:

  • scala 2.13.0
  • "org.reactivemongo" %% "reactivemongo" % "0.18.6"

Is for me I've done as it was required following documentation. But compilation issues appeared near each DB operation (personCollection: insert, update, find). I'm not clear how to fix ones because of lack scala knowledge\experience.

The code:

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
import scala.util.Try
import reactivemongo.api.{Cursor, DefaultDB, MongoConnection, MongoDriver}
import reactivemongo.bson.{BSONDocumentReader, BSONDocumentWriter, Macros, document}

object GetStartedWithMongo {
  def main(args: Array[String]): Unit = {
    val age = 99
    val person: Person = Person("firstName", "lastName", age)
    createPerson(person)
    findPersonByAge(age).andThen {
      case x => println(s"loaded data: $x")
    }

    println("completed")
  }

  val database = "personDb"
  val driver = new MongoDriver
  val mongoUri = "mongodb://localhost:27017/mydb?authMode=scram-sha1"
  // Connect to the database: Must be done only once per application
  val parsedUri: Try[MongoConnection.ParsedURI] =
    MongoConnection.parseURI(mongoUri)
  val connection: Try[MongoConnection] = parsedUri.map(driver.connection(_))
  val futureConnection: Future[MongoConnection] = Future.fromTry(connection)

  //  val db = connection(database)
  val db: Future[DefaultDB] = futureConnection.flatMap(_.database(database))

  //  def personCollection: Future[List[Person]] = db.map(_.collection("person"))
  def personCollection = db.map(_.collection("person"))

  // use personWriter
  def createPerson(person: Person): Future[Unit] =
    personCollection.flatMap(_.insert.one(person).map(_ => {}))
//                             ^^^^^^ - compilation issue

  // Write Documents: insert or update

  implicit def personWriter: BSONDocumentWriter[Person] = Macros.writer[Person]
  // or provide a custom one

  def updatePerson(person: Person): Future[Int] = {
    val selector =
      document("firstName" -> person.firstName, "lastName" -> person.lastName)

    // Update the matching person
    personCollection.flatMap(_.update.one(selector, person).map(_.n))
//                             ^^^^^^ - compilation issue

  }

  implicit def personReader: BSONDocumentReader[Person] = Macros.reader[Person]
  // or provide a custom one

  def findPersonByAge(age: Int): Future[List[Person]] =
    personCollection.flatMap(
      _.find(document("age" -> age)). // query builder
//      ^^^^ - compilation issue

      cursor[Person](). // using the result cursor
      collect[List](-1, Cursor.FailOnError[List[Person]]())
    )
  // ... deserializes the document using personReader

  // Custom persistent types
  case class Person(firstName: String, lastName: String, age: Int)
}

P.S.

To make it more easier consider and fix issue I've shared this experimental module via git (the class).

cchantep
  • 9,118
  • 3
  • 30
  • 41
Sergii
  • 7,044
  • 14
  • 58
  • 116

2 Answers2

2

To make it compile, add an explicit type annotation to personCollection:

def personCollection: Future[BSONCollection] = db.map(db => db.collection("person"))
bszwej
  • 420
  • 4
  • 9
0

Checking other reactivemongo tutorial pages we can specify dbCollection type. Return type is not Future[List[Person]] or Future[Person] or Future[Nothing]. It is Future[BSONCollection]. If type is added compilation issues are fixed.

Starting project we can find in terminal messages that something else missed. To fix missed dependency I've added to project slf4j library ("org.slf4j" % "slf4j-api" % "1.7.28")

So if I try this:

def main(args: Array[String]): Unit = {
  val age = 93
  val person: Person = Person("firstName", "lastName", age)
  createPerson(person)
  findPersonByAge(age).andThen {
    case x => println(s"loaded data: $x")
  }

  println("completed")
}

the result as expected in general:

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
completed
ERROR StatusLogger Log4j2 could not find a logging implementation. Please add log4j-core to the classpath. Using SimpleLogger to log to the console...
loaded data: Success(List(Person(firstName,lastName,93)))

Git is updated also.

Sergii
  • 7,044
  • 14
  • 58
  • 116