mongodbscalaplayframeworkcasbahsalat

Casbah: No implicit view available error


In a Play app, using Salat and Casbah, I am trying to de-serialize a DBObject into an object of type Task, but I am getting this error when calling .asObject:

No implicit view available from com.mongodb.casbah.Imports.DBObject => com.mongodb.casbah.Imports.MongoDBObject. Error occurred in an application involving default arguments.

The object is serialized correctly with .asDBObject, and written to the database as expected.

What is causing this behaviour, and what can be done to solve it? Here's the model involved:

package models

import db.{MongoFactory, MongoConnection}

import com.novus.salat._
import com.novus.salat.global._
import com.novus.salat.annotations._
import com.mongodb.casbah.Imports._
import com.mongodb.casbah.commons.Imports._
import play.api.Play


case class Task(label: String, _id: ObjectId=new ObjectId)

object Task {

  implicit val ctx = new Context {
    val name = "Custom_Classloader"
  }

  ctx.registerClassLoader(Play.classloader(Play.current))

  val taskCollection = MongoFactory.database("tasks")

  def create(label: String): Task = {
    val task = new Task(label)
    val dbObject = grater[Task].asDBObject(task)
    taskCollection.save(dbObject)
    grater[Task].asObject(dbObject)
  }

  def all(): List[Task] = {
    val results = taskCollection.find()
    val tasks = for (item <- results) yield grater[Task].asObject(item)
    tasks.toList
  }
}

Versions

casbah: "2.8.1"
scala: "2.11.6"
salat: "1.9.9"

Solution

  • Instructions on creating a custom context:

    • First, define a custom context as implicit val ctx = new Context { /* custom behaviour */ } in a package object
    • Stop importing com.novus.salat.global._
    • Import your own custom context everywhere instead.

    Source: https://github.com/novus/salat/wiki/CustomContext