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

时间:2017-02-05 00:09:33

标签: scala playframework reactivemongo play-reactivemongo

我使用的是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>

}

1 个答案:

答案 0 :(得分:0)

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

=&GT;控制器方法Bind the form request中的registerPost。为此,您还需要form mapping设置。此映射将帮助您使用方法内的表单数据生成UserModel对象。要做到这一切,请参阅此处ScalaForms

=&GT;你这里不需要writes。您可以使用format同时执行json writes and reads

=&GT;现在将UserModel转换为JsValue:

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

=&GT;然后,您只需将存储库称为:

collection.insert(userModelJson)