Below is my simple document that represents a Link. I am using reactivemongo in scala for this.
I am getting this error during compilation:
app/components/Link.scala:60:11: No Json deserializer found for type components.Link. Try to implement an implicit Reads or Format for this type. [error] .one[Link]) [error] ^ [error] one error found
I created the implicits in my Link companion object, which I also imported into my LinkRepo class.
Am I handling the mongo document _id correctly?
Should I use a String to map to the document ID, confused as to what is the best practise? Do I have to convert the String to the BSONObjectID at some point?
package components
import javax.inject.Inject
import reactivemongo.bson._
import reactivemongo.api.ReadPreference
import reactivemongo.api.collections.bson.BSONCollection
import reactivemongo.bson.{ BSONDocument, BSONObjectID }
import reactivemongo.api.commands.{ UpdateWriteResult, WriteResult, Upserted }
import reactivemongo.api.commands.bson.BSONUpdateCommand._
import reactivemongo.api.commands.bson.BSONUpdateCommandImplicits._
case class Link(id: Link.ID,
name: String,
url: String)
object Link {
type ID = String
implicit val linkReader: BSONDocumentReader[Link] =
BSONDocumentReader[Link] { doc: BSONDocument =>
Link(
doc.getAs[String]("id").getOrElse(""),
doc.getAs[String]("name").getOrElse(""),
doc.getAs[String]("url").getOrElse(""))
}
implicit val linkWriter: BSONDocumentWriter[Link] =
BSONDocumentWriter[Link] { link: Link =>
BSONDocument(
"id" -> link.id,
"name" -> link.name,
"url" -> link.url)
}
}
import scala.concurrent.{ ExecutionContext, Future }
import reactivemongo.bson.{ BSONDocument, BSONObjectID }
import reactivemongo.api.{ Cursor, ReadPreference }
import reactivemongo.api.commands.WriteResult
import reactivemongo.play.json._
import reactivemongo.play.json.collection.JSONCollection
import play.modules.reactivemongo.ReactiveMongoApi
class LinkRepo @Inject()(implicit ec: ExecutionContext, reactiveMongoApi: ReactiveMongoApi) {
import Link._
def linksCol: Future[JSONCollection] = reactiveMongoApi.database.map(_.collection("links"))
def byId(id: Link.ID): Future[Option[Link]] = {
linksCol.flatMap(_.find(
selector = BSONDocument("_id" -> id),
projection = Option.empty[BSONDocument])
.one[Link])
}
}
My sbt has these lib versions:
scalaVersion := "2.12.7"
libraryDependencies += guice
libraryDependencies ++= Seq(
guice,
"joda-time" % "joda-time" % "2.9.9",
"net.ruippeixotog" %% "scala-scraper" % "2.1.0",
"org.reactivemongo" %% "play2-reactivemongo" % "0.16.0-play26",
"org.scalatestplus.play" %% "scalatestplus-play" % "3.1.2" % Test
)
plugins:
addSbtPlugin("com.typesafe.play" % "sbt-plugin" % "2.6.20")