gre*_*per 6 scala reactivemongo
我正在用akka-http和ReactiveMongo编写一个Web服务.我遇到了问题,我无法自己解决.
我有方法
def saveRoute(route: Route)(implicit writer: BSONDocumentWriter[Route]): Future[WriteResult] = {
collection.insert(route)
}
Run Code Online (Sandbox Code Playgroud)
问题是WriteResult除了错误或OK状态之外不包含任何有用的信息.
你能解释一下如何在插入后获取插入的对象ID.我发现的所有示例都LastError与Play 版本的旧版本有关!框架.
这是ReactiveMongo制作的(相当常见的)设计选择.
建议的解决方案是自己提供一个id BSONObjectID.generate,而不是让db为你创建一个id .
以下是ReactiveMongo文档的示例http://reactivemongo.org/releases/0.11/documentation/tutorial/write-documents.html
val id = BSONObjectID.generate
val person = Person(
id,
"Stephane",
"Godbillon",
29)
val future = collection.insert(person)
future.onComplete {
case Failure(e) => throw e
case Success(lastError) => {
println(s"successfully inserted document with id $id)
}
}
Run Code Online (Sandbox Code Playgroud)
我设法通过从 save 方法返回元组来获取 ID 或任何其他字段,甚至整个对象。
def saveRoute(route: Route)(implicit writer: BSONDocumentWriter[Route]) = {
collection.insert(route).map((_, route))
}
Run Code Online (Sandbox Code Playgroud)
我Route在调用之前复制实体并分配生成的 IDsaveRoute
route.copy(id = Some(BSONObjectID.generate().stringify))
Run Code Online (Sandbox Code Playgroud)
这种方法允许我同时获取 WriteResult 和保存的实体