blue-sky blue-sky - 1 month ago 25
Scala Question

How to setup Play!2.5 with ReactiveMongo

I connect to MongoDB with Scala using :

val driver = new MongoDriver
val connection = driver.connection(List("myhost"))
val db = connection.database("mydb")


This works fine but how to integrate this with a Play controller :

@Singleton
class ReactiveController @Inject() (implicit system: ActorSystem, materializer: Materializer, val reactiveMongoApi: ReactiveMongoApi)
extends Controller with MongoController with ReactiveMongoComponents {


Do I need to inject a custom
ReactiveMongoApi
with my DB configuration ?

Or do I need to modify application.conf with my DB settings ?

I'm using play 2.5 and http://reactivemongo.org/releases/0.11/documentation/tutorial/play2.html provides this code :

package api

import reactivemongo.api.{ DB, MongoConnection, MongoDriver }

trait ReactiveMongoApi {
def driver: MongoDriver
def connection: MongoConnection
def db: DB
}


But I'm unsure how to integrate it with my Play application ?

I think I'm not aware of some standard method of configuring DB sources with a Play! application ?

Answer

Make sure you have correct configs in application.conf

play.modules.enabled += "play.modules.reactivemongo.ReactiveMongoModule"
mongodb.uri = "mongodb://localhost:27017/demodb"

You need to inject and change mongo code as below

class MongoUserDao @Inject() (val reactiveMongoApi: ReactiveMongoApi)
extends UserDao {
//  val users = reactiveMongoApi.db.collection[JSONCollection]("users") -- old API
//   def find(userId:UUID):Future[Option[User]] =
//    users.find(Json.obj("id" -> userId)).one[User]  -- old code

  def usersF = reactiveMongoApi.database.map(_.collection[JSONCollection]("users"))  //new API

  def find(userId:UUID):Future[Option[User]] = for {
    users <- usersF
    user <- users.find(Json.obj("id" -> userId)).one[User]
  } yield user     // new code
}

If you compare new api code with old api code, reactiveMongoApi.database.map returns Furure[collection].

Thanks Pari

Comments