Mongodb 使用ReactiveMongo更新后的模式匹配
在使用scala更新mongodb上的文档后,我尝试进行模式匹配以检查错误Mongodb 使用ReactiveMongo更新后的模式匹配,mongodb,scala,reactivemongo,Mongodb,Scala,Reactivemongo,在使用scala更新mongodb上的文档后,我尝试进行模式匹配以检查错误 def update(id: BSONObjectID, post: Post): Future[WriteResult] = collection.flatMap(_.update.one(BSONDocument("_id" -> id), BSONDocument( f"$$set" -> BSONDocument( "title" -> post.title, "descri
def update(id: BSONObjectID, post: Post): Future[WriteResult] =
collection.flatMap(_.update.one(BSONDocument("_id" -> id), BSONDocument(
f"$$set" -> BSONDocument(
"title" -> post.title,
"description" -> post.description
)
),
true))
这是我在productrepository中的更新功能,这是我的控制器
def update (id: String) = Action.async(parse.json) { /*implicit request =>*/
val bsonId = BSONObjectID.parse(id)
_.body.validate[Post].map { post =>
postsRepo.update(bsonId.get, post).map {
case Some(post) => Ok(Json.toJson(post))
case _ => NotFound
// _ => Created
}
}.getOrElse(Future.successful(BadRequest("Invalid Format")))
}
我得到这个错误:
constructor cannot be istantiated to expected type;
Found Some[A]
Required Reactivemongo.api.command.writeResult
我的目标是在更新后运行模式匹配如果您查看IDE/编译器消息,您可以看到is
Future[UpdateWriteResult]
,因此在Future.map中的选项
上进行匹配不能正常
如果您阅读,您会发现一个“错误处理”部分,解释如何根据DB代码或消息恢复写入结果
val done: Future[Unit] = future.map(_ => {}).recover {
case WriteResult.Code(11000) =>
// if the result is defined with the error code 11000 (duplicate error)
println("Match the code 11000")
case WriteResult.Message("Must match this exact message") =>
println("Match the error message")
case _ => ()
}
如果您试图在未更新任何内容的情况下生成特定响应,则不需要使用模式匹配,只需在.map
中检查(已更新文档的数量)