Scala Play 将请求转换为 JSON 并将其写入 MongoDB

Scala Play convert a request to JSON and write it to MongoDB

我正在使用 Play 2.5 和 ReactiveMongo。这是一个简单的问题,但我无法弄清楚。我有一个从视图接收 usernamepassword 的控制器,我想将此请求转换为 UserModel 类型的模型,然后将此模型转换为 json 和写到 MongoDB.

我的控制器:

class RegisterController @Inject() (val reactiveMongoApi: ReactiveMongoApi) 
extends Controller with MongoController with ReactiveMongoComponents {

  def registerPost = Action.async { request =>

  implicit val accountWrites = new Writes[UserModel] {
  def writes(account: UserModel) = Json.obj(
    "username" -> account.username,
    "password" -> account.password
  )
} //needs this for some reason?

val future = collection.insert(request.body) //trying to insert to mongo
future.map(_ => Ok)

我的模特:

case class UserModel(username: String, password: String) {}

object UserModel {

  implicit val format = Json.format[UserModel] //needs this for some reason?

  val userModel = Form(
mapping(
  "username" -> nonEmptyText,
  "password" -> nonEmptyText
)(UserModel.apply)(UserModel.unapply))
}

我的看法:

@(userForm: Form[UserModel])(implicit messages: Messages)

<h1>Register</h1>

@helper.form(action = routes.RegisterController.registerPost()) {
  @helper.inputText(userForm("username"))
  @helper.inputText(userForm("password"))

  <button type="submit" name="action" value="register">Register</button>

}

这些是您需要做的关键事情:

=> Bind the form request 在你的控制器方法中,registerPost。为此,您还需要进行 form mapping 设置。此映射将帮助您使用方法内的表单数据生成 UserModel 对象。要执行所有这些操作,请参阅此处 ScalaForms

=> 这里不需要 writes。您可以使用 format 执行两个 json writes and reads.

=> 现在将 UserModel 转换为 JsValue 为:

//usermodel will be generated by binding the form data
implicit val format = Json.format[UserModel]
val userModelJson = format.writes(usermodel)

=> 然后你可以简单地调用存储库:

collection.insert(userModelJson)