0

I am new to Play (and somewhat new to Scala), so forgive me if this is way off the mark, though really that is why I am posting this here.

I'm trying to create a basic endpoint which goes away and does basic CRUD with mongodb.

controllers/NoteController.scala:

package controllers

import play.api.mvc._
import play.api.libs.json._
import data.Note

class NotesController extends Controller {

  def index = Action {
    Note.fetch match {
      case Some(notes) => Ok(Json.toJson(notes))
      case None => NotFound
    }
  }

  def show(id: Long) = Action {
    val note = Note.fetch(id)

    note match {
      case Some(note) => Ok(Json.toJson(note))
      case None => NotFound
    }
  }
}

data/Note.scala

package data

import com.mongodb.casbah.Imports._

object Note {

  def fetch = {
    Mongo.db("note").find
  }

  def fetch(id: Long) = {
    Mongo.db("note").findOne(
      MongoDBObject("id" -> id)
    )
  }
}

The above code doesn't actually work, but I've been banging my head against a wall for the last couple of days attempting to figure out how to get it to. I've tried using the JSON serializer that comes with casbah but had no joy there either. I just can't seem to work out how to go from the mongo data (from DBObject) to presenting the relevant JSON.

Edit:

As mentioned in a comment to this question, the above outputs:

No Json serializer found for type Any. Try to implement an implicit Writes or Format for this type.

When it gets the the point in the code it is attempting to serialize note as json: Ok(Json.toJson(note))

danbroooks
  • 2,712
  • 5
  • 21
  • 43
  • What does this code output? I haven't tried using Play with Mongo before but I know the Json.toJson will convert either a String in JSON format or a plain object ("bean") to JSON. So I would guess that Note.fetch doesn't return either of these things? – Scott Shipp Oct 19 '16 at 19:34
  • No, this is a simplified version of what I have, but effectively just what I am trying to do, I'm guessing it errors to say it is passing an inappropriate value to `Json.toJson`. I'll run it and put the output into the question now. – danbroooks Oct 19 '16 at 19:35
  • I would recommend using the more modern MongoDB Scala Driver (http://mongodb.github.io/mongo-scala-driver). The `Document` class has a toJson method that would simplify the creation of the Json strings. – Ross Oct 20 '16 at 04:14

1 Answers1

0

I suggest you declare the expected return type on all the methods you use. It will show you where your problem is. I'm guessing you think you're returning a List[JsValue] from Node.fetch, but you're actually returning Any for some reason.

Zoltán
  • 21,321
  • 14
  • 93
  • 134