DuplicateKey的解决方案:E11000重复键错误索引与Play! 2.0框架

时间:2012-08-12 21:12:44

标签: scala playframework-2.0

我正在使用play-salat插件和我正在播放的应用程序! 2.0 scala。

我收到Duplicate Key错误,编译器指向错误:

object Post extends ModelCompanion[Post, ObjectId]

我已经读过,这可以在PHP here中修复,但请告诉我如何使用Play进行此操作。

我可以在我的数据库中发布一次,当我再次尝试时,我得到错误。

def save = Action { implicit request =>
postForm.bindFromRequest.fold(
  formWithErrors => BadRequest(html.newpost(formWithErrors)),
  post => {
    Post.insert(post)
    Home
  }
)
}

val postForm = Form(
mapping(
  "_id" -> ignored(new ObjectId()),
  "title" -> nonEmptyText,
  "content" -> nonEmptyText,
  "posted" -> date("yyyy-MM-dd"),
  "modified" -> optional(date("yyyy-MM-dd")),
  "tags" -> nonEmptyText,
  "categories" -> nonEmptyText,
  "userId" -> nonEmptyText
)(Post.apply)(Post.unapply)
) 

1 个答案:

答案 0 :(得分:0)

我自己解决了这个问题。我是Scala和Play Framework的新手。

我改变了我的Application.scala文件:

def newpost = Action {
Ok(views.html.newpost(postForm))
}

def save = Action { implicit request =>
postForm.bindFromRequest.fold(
  formWithErrors => BadRequest(html.newpost(formWithErrors)),
  post => {
    Post.create(post.title, post.content, post.posted, post.modified, post.categories, post.tags, post.author)
    Home.flashing("success" -> "Post %s has been created".format(post.title))
  }
)
}

val postForm = Form(
mapping(
  "_id" -> ignored(new ObjectId()),
  "title" -> nonEmptyText,
  "content" -> nonEmptyText,
  "posted" -> date("yyyy-MM-dd"),
  "modified" -> optional(date("yyyy-MM-dd")),
  "categories" -> nonEmptyText,
  "tags" -> nonEmptyText,
  "author" -> nonEmptyText
)(Post.apply)(Post.unapply)
)

我还更改了Post.scala文件:

 object PostDAO extends SalatDAO[Post, ObjectId](
collection = MongoConnection()("blog")("posts"))

 object Post {

  def create(title: String, content: String, posted: Date = new Date(), modified: Option[Date] = None, categories: String, tags: String, author: String) {
    PostDAO.insert(Post(
        title = title,
        content = content,
        posted = posted,
        modified = modified,
        categories = categories,
        tags = tags,
        author = author
        ))
  }

  def delete(id: String) {
    PostDAO.remove(MongoDBObject("_id" -> new ObjectId(id)))
}
}