green-creeper green-creeper - 1 year ago 214
Scala Question

Get ID after insert with ReactiveMongo

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] = {

The problem is
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
or with Play! Framework.

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download