本文介绍了如何使用ReactiveMongo设置Play!2.5的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下命令通过Scala连接到MongoDB:

I connect to MongoDB with Scala using :

val driver = new MongoDriver
val connection = driver.connection(List("myhost"))
val db = connection.database("mydb")

这很好用,但是如何将其与Play控制器集成:

This works fine but how to integrate this with a Play controller :

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

我是否需要使用数据库配置注入自定义ReactiveMongoApi?

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

还是我需要使用数据库设置来修改application.conf?

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

我正在使用play 2.5和 http://reactivemongo.org/releases /0.11/documentation/tutorial/play2.html 提供了以下代码:

I'm using play 2.5 and http://reactivemongo.org/releases/0.11/documentation/tutorial/play2.html provides this code :

package api

import reactivemongo.api.{ DB, MongoConnection, MongoDriver }

trait ReactiveMongoApi {
  def driver: MongoDriver
  def connection: MongoConnection
  def db: DB
}

但是我不确定如何将其与Play应用程序集成吗?

But I'm unsure how to integrate it with my Play application ?

我想我不知道使用Play配置数据库源的一些标准方法!应用程序?

I think I'm not aware of some standard method of configuring DB sources with a Play! application ?

推荐答案

确保在application.conf中具有正确的配置

Make sure you have correct configs in application.conf

play.modules.enabled += "play.modules.reactivemongo.ReactiveMongoModule"
mongodb.uri = "mongodb://localhost:27017/demodb"

您需要按如下所示注入和更改mongo代码

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 = 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代码进行比较,则reactMongoApi.database.map将返回Future [Collection].

If you compare new api code with old api code, reactiveMongoApi.database.map returns Future[Collection].

这篇关于如何使用ReactiveMongo设置Play!2.5的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-27 06:49