I'm working in a spray, akka, scala, reactivemongo project and I have this trait

trait PersistenceManager {

  val driver = new MongoDriver
  val connection = driver.connection(List("localhost"))

  def loan[A](collectionName: String)(f: BSONCollection => Future[A]): Future[A] = {
    val db = connection("flujo_caja_db")
    val collection = db.collection(collectionName)
    f(collection)
  }
}

Also I have Dao's objects to use that trait like so:

object Dao extends PersistenceManager {

   def find = loan("users"){
     collection =>
          collection.find(BsonDocument())....
   }

}

It is correct to instanciate those database vals in my persistencemanager trait? It works really good.

Thank you!

有帮助吗?

解决方案

I'm thinking you want things defined like this, to prevent multiple MongoDriver and connection pools from being created:

object PersistenceManager{
  val driver = new MongoDriver
  val connection = driver.connection(List("localhost"))
}


trait PersistenceManager {
  import PersistenceManager._

  def loan[A](collectionName: String)(f: BSONCollection => Future[A]): Future[A] = {
    val db = connection("flujo_caja_db")
    val collection = db.collection(collectionName)
    f(collection)
  }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top