【问题标题】:How to setup Play!2.5 with ReactiveMongo如何使用 ReactiveMongo 设置 Play!2.5
【发布时间】:2016-05-25 18:05:15
【问题描述】:

我使用 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! 配置数据库源的一些标准方法!申请?

【问题讨论】:

  • 如果您阅读了问题中链接的文档,您可以看到“配置您的数据库访问”部分,这表明您需要在application.conf 中添加mongodb.uri 设置跨度>
  • 并添加 play.modules.enabled += "play.modules.reactivemongo.ReactiveMongoModule"
  • 如果您想要一个带有最新 MongoDB 驱动程序的 Play 2.5 工作示例作为参考,请查看lightbend.com/activator/template/play-reactive-mongo-db

标签: mongodb scala playframework reactivemongo


【解决方案1】:

确保您在 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]。

【讨论】:

  • 我不明白这是如何工作的。 ReactiveMongoApi,我理解得很好,没有一个名为“数据库”的属性,如果我写“db”我不能在之后调用“map”。我应该从另一个地方导入“reactiveMongoApi”吗? @Pariksheet_Barapatre 谢谢你的回答
  • 这些是 0.11 版本中引入的新 API。确保您使用“org.reactivemongo”%%“play2-reactivemongo”%“0.11.14”,导入语句将是-import play.modules.reactivemongo.ReactiveMongoApi
猜你喜欢
  • 2017-07-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-10
  • 1970-01-01
  • 2015-05-08
  • 2013-08-29
  • 1970-01-01
相关资源
最近更新 更多