Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 371
green-creeper Avatar asked Sep 06 '16 16:09

green-creeper


Video Answer


1 Answers

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)
  }
}
like image 142
Gabriele Petronella Avatar answered Oct 07 '22 08:10

Gabriele Petronella