I'm writing a web service with akka-http and ReactiveMongo. I faced with problem, which I unable to resolve by myself.
I have method
def saveRoute(route: Route)(implicit writer: BSONDocumentWriter[Route]): Future[WriteResult] = {
collection.insert(route)
}
The problem is WriteResult
doesn't contain any useful information except error or OK status.
Could you please explain how to get inserted object ID after insert.
All examples which I've found are either related to old version with LastError
or with Play! Framework.
That's a (fairly common) design choice made by ReactiveMongo.
The recommended solution is to provide an id yourself, using BSONObjectID.generate
, instead of letting the db create one for you.
Here's an example from the ReactiveMongo documentation 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)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With