6

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.

cchantep
  • 9,118
  • 3
  • 30
  • 41
green-creeper
  • 316
  • 3
  • 15

2 Answers2

7

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)
  }
}
Gabriele Petronella
  • 106,943
  • 21
  • 217
  • 235
1

I managed to get ID or any other field, or even entire object by returning tuple from save method.

def saveRoute(route: Route)(implicit writer: BSONDocumentWriter[Route]) = {
    collection.insert(route).map((_, route))
  }

I copy Route entity and assign genereted ID before invoke saveRoute

route.copy(id = Some(BSONObjectID.generate().stringify))

This approach allows me to get both, WriteResult and saved entity

green-creeper
  • 316
  • 3
  • 15