我使用Scala连接到使用Scala的MongoDB:
val driver = new MongoDriver
val connection = driver.connection(List("myhost"))
val db = connection.database("mydb")
这很好但是如何将它与Play控制器集成:
@Singleton
class ReactiveController @Inject() (implicit system: ActorSystem, materializer: Materializer, val reactiveMongoApi: ReactiveMongoApi)
extends Controller with MongoController with ReactiveMongoComponents {
我是否需要使用我的数据库配置注入自定义ReactiveMongoApi
?
或者我是否需要使用我的数据库设置修改application.conf?
我正在使用play 2.5和http://reactivemongo.org/releases/0.11/documentation/tutorial/play2.html提供此代码:
package api
import reactivemongo.api.{ DB, MongoConnection, MongoDriver }
trait ReactiveMongoApi {
def driver: MongoDriver
def connection: MongoConnection
def db: DB
}
但我不确定如何将其与我的Play应用程序集成?
我想我不知道使用Play配置数据库源的一些标准方法!申请?
答案 0 :(得分:4)
确保application.conf中有正确的配置
play.modules.enabled += "play.modules.reactivemongo.ReactiveMongoModule"
mongodb.uri = "mongodb://localhost:27017/demodb"
您需要注入和更改mongo代码,如下所示
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
}
如果将新的api代码与旧的api代码进行比较,则reactiveMongoApi.database.map将返回Future [Collection]。