blue-sky blue-sky - 11 days ago 7
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 :

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

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

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

I'm using play 2.5 and 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 ?


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 =[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, returns Furure[collection].

Thanks Pari