使用 ReactiveMongo 进行 CRUD 操作

Make CRUD operations with ReactiveMongo

我最近开始学习 scala,并尝试使用 akka HTTP 和 reactivemongo 创建简单的 api。 简单的操作有问题。花很多时间挖 docks、官方教程、Whosebug 等。可能我遗漏了一些很简单的东西。

我的代码:

object MongoDB {
    val config = ConfigFactory.load()
    val database = config.getString("mongodb.database")
    val servers = config.getStringList("mongodb.servers").asScala
    val credentials = Lis(Authenticate(database,config.getString("mongodb.userName"), config.getString("mongodb.password")))
    val driver = new MongoDriver
    val connection = driver.connection(servers, authentications = credentials)
    //val db = connection.database(database)
}

现在我想做基本的CRUD操作。我正在尝试不同的代码片段,但无法正常工作。

这里有一些例子:

object TweetManager {
    import MongoDB._
    //taken from docs
    val collection = connection.database("test").
        map(_.collection("tweets"))
    val document1 = BSONDocument(
        "author" -> "Tester",
        "body" -> "test"
    )

    //taken from reactivemongo tutorial, it had extra parameter as BSONCollection, but can't get find the way of getting it
    def insertDoc1(doc: BSONDocument): Future[Unit] = {
        //another try of getting the collection
        //def collection = for ( db1 <- db) yield db1.collection[BSONCollection]("tweets") 
        val writeRes: Future[WriteResult] = collection.insert(doc)
        writeRes.onComplete { // Dummy callbacks
            case Failure(e) => e.printStackTrace()
            case Success(writeResult) =>
                println(s"successfully inserted document with result: $writeResult")
        }
        writeRes.map(_ => {}) // in this example, do nothing with the success
    }
}
insertDoc1(document1)

我无法对集合进行任何操作。 IDE 给我:"cannot resolve symbol"。编译器给出错误:

value insert is not a member of scala.concurrent.Future[reactivemongo.api.collections.bson.BSONCollection]

正确的做法是什么?

您正在尝试对 Future[Collection] 而不是基础集合调用 insert 操作(调用 Future[T] 而不是 T 的操作不是特定于 ReactiveMongo)。

推荐看一下documentation