我是 Reactivemongo 数据库(2.6)的新手,因为我正在尝试从我的本地系统上传/插入 json 对象(它是键/值对,我在单击我的 UI 中的提交按钮后将其发送到数据库中)到使用 Play Framework/Scala 存储在 Mongodb 中(使用 Play 2.2.3 和 2.3.8 进行了尝试)。我试过了:
import play.api.libs.json.{JsObject, JsValue, OWrites}
import play.api.mvc.{Action, Controller}
import play.modules.reactivemongo.MongoController
import play.modules.reactivemongo.json.collection._
import scala.concurrent.ExecutionContext.Implicits.global
object Application extends Controller with MongoController {
def jsinfocollection: JSONCollection = db.collection[JSONCollection]("mycollection")
implicit val jsvalueWrites = new OWrites[JsValue] {
println("implicit val jsvalueWrites ...")//getting the message on Play console
override def writes(o: JsValue): JsObject = o match {
case o : JsObject => o
case _ => throw new IllegalArgumentException("Only JsObjects can be stored")
}
}
def createJson = Action.async(parse.json) {
println("createJson calling...")//getting the message on Play console
request =>
jsinfocollection.insert(request.body).map{
println("jsinfocollection.insert...")//getting the message on Play console
r => Created(s"JsonInfo is Saved with result $r")
}
}
}
我已经在 Mongodb 中创建了一个集合,例如:>db.createCollection("mycollection")
{ "ok" : 1 }
但如果我给:>db.mycollection.count()
- 是给 0,否则如果我给:db.mycollection.find()
- 什么都不给
请让我知道如何将我的 json 数据插入我所需的集合("mycollection"
)中。提前致谢。
我在控制台上得到以下信息:
implicit val jsvalueWrites ...
createJson calling...
jsinfocollection.insert...
[error] play - Cannot invoke the action, eventually got an error: java.lang.IllegalArgumentException: Only JsObjects can be stored
Internal server error, for (POST) [/createJson]