Get id after insert using ReactiveMongo

I am writing a web service with akka-http and ReactiveMongo. I ran into a problem that I could not solve myself.

I have a method

def saveRoute(route: Route)(implicit writer: BSONDocumentWriter[Route]): Future[WriteResult] = { collection.insert(route) } 

Problem WriteResult does not contain any useful information other than an error or an OK status.

Could you please explain how to get the inserted object id after insertion. All the examples I found are either related to the old version with LastError , or with Play! Framework

+5
source share
2 answers

I managed to get the identifier or any other field or even the whole object, returning the tuple from the save method.

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

I copy the Route object and assign an ID generator before calling saveRoute

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

This approach allows me to get both WriteResult and saved entity

+1
source

This is a (fairly general) design made by ReactiveMongo.

The recommended solution is to provide the identifier yourself using BSONObjectID.generate instead of letting db create it for you.

Here is 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) } } 
+5
source

All Articles