I have the following function that uses the reactivemongo driver and actually does a good job writing to the database.
def writeDocument() = {
val docume
The ReactiveMongo release note notes:
When using the support for Play JSON, if the previous error occurs, it necessary to make sure import reactivemongo.play.json._ is used, to import default BSON/JSON conversions.
First, you could serialize your model classes as BSON using reactivemongo. Check docs to see how.
If you want to make a BSONDocument
from String
through play json you can use
val playJson: JsValue = Json.parse(jsonString)
val bson: BSONDocument = play.modules.reactivemongo.json.BSONFormats.reads(playJson).get
Edit
I found more in the docs here:
http://reactivemongo.org/releases/0.11/documentation/tutorial/play2.html
you can import those two
import reactivemongo.play.json._
import play.modules.reactivemongo.json.collection._
Instead of using the default Collection implementation (which interacts with BSON structures + BSONReader/BSONWriter), we use a specialized implementation that works with JsObject + Reads/Writes.
So you create specialized collection like this (must be def
, not val
):
def collection: JSONCollection = db.collection[JSONCollection]("persons")
and from now on you can use it with play json, instead of BSON, so simply passing in Json.parse(jsonString)
as a document to insert should work. You can see more examples in the link.
Edit 2 I got your code to compile:
package controllers
import play.api.libs.concurrent.Execution.Implicits._
import play.api.libs.json._
import play.modules.reactivemongo.json.collection.{JSONCollection, _}
import reactivemongo.api.MongoDriver
import reactivemongo.play.json._
import play.api.libs.json.Reads._
import scala.util.{Failure, Success}
object Mongo {
def collection: JSONCollection = {
val driver = new MongoDriver
val connection = driver.connection(List("localhost"))
val db = connection("superman")
db.collection[JSONCollection]("IncomingRequests")
}
def writeDocument() = {
val jsonString = """{
| "guid": "alkshdlkasjd-ioqweuoiquew-123132",
| "title": "Hello-2016",
| "year": 2016,
| "action": "POST",
| "start": "2016-12-20",
| "stop": "2016-12-30"}"""
val document = Json.parse(jsonString).as[JsObject]
val future = collection.insert(document)
future.onComplete {
case Failure(e) => throw e
case Success(result) =>
println("successfully inserted document with result = " + result)
}
}
}
the important import is
import play.api.libs.json.Reads._
and you need JsObject
, not just any JsValue
val document = Json.parse(jsonString).as[JsObject]