Skip to content

Instantly share code, notes, and snippets.

@maiostri
Created July 14, 2014 14:22
Show Gist options
  • Save maiostri/627491f56998d85a1ed1 to your computer and use it in GitHub Desktop.
Save maiostri/627491f56998d85a1ed1 to your computer and use it in GitHub Desktop.
Generic DAO using ReactiveMongo
package models.dao
import scala.concurrent.ExecutionContext
import scala.concurrent.Future
import play.api.Play.current
import play.modules.reactivemongo.ReactiveMongoPlugin
import reactivemongo.api.collections.default.BSONCollection
import reactivemongo.bson.BSONDocument
import reactivemongo.bson.BSONDocumentIdentity
import reactivemongo.bson.BSONDocumentReader
import reactivemongo.bson.BSONDocumentWriter
import reactivemongo.core.commands.LastError
trait MongoDAO[T] {
implicit val ec: ExecutionContext
implicit val reader: BSONDocumentReader[T]
val collectionName: String
def db = ReactiveMongoPlugin.db
def collection = db[BSONCollection](collectionName)
def insert[T](document: T)(implicit writer: BSONDocumentWriter[T]): Future[LastError] = {
collection.insert(document)
}
def findAll(implicit reader: BSONDocumentReader[T]): Future[List[T]] = {
collection.find(BSONDocument()).cursor[T].collect[List]()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment