使用ReactiveMongo进行CRUD操作

时间:2016-10-22 17:54:13

标签: scala reactivemongo

我最近开始学习scala并尝试使用akka HTTP和reactivemongo创建简单的api。 操作简单有问题。花了很多时间挖掘码头,官方教程,stackoverflow等。可能我错过了一些非常简单的东西。

我的代码:

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给了我:&#34;无法解析符号&#34;。编译器给出错误:

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

这样做的正确方法是什么?

1 个答案:

答案 0 :(得分:0)

您正尝试在insert上调用Future[Collection]操作,而不是在基础集合上调用Future[T]上的调用操作而不是T上的调用操作不是特定于begin MY_PROCEDURE( :start_id, :end_id ); end; ReactiveMongo)。

建议您查看documentation