n0wy n0wy - 5 months ago 55
Scala Question

make crud opperations in reactivemongo

I have started to learn scala recently and trying to create simple api using akka HTTP and reactivemongo.
Have problems with simple operations. Spend a lot of time digging docks, official tutorials, stackoverflow etc. Probably I am missing something very simple.
My code:
I resolve collection

object MongoDB {
val config = ConfigFactory.load()
val database = config.getString("mongodb.database")
val servers = config.getStringList("mongodb.servers").asScala
val credentials = List(
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)

Now I would like to make basic crud operations. I am trying different code snippets but can't get it working.
Here are some examples:

object TweetManager {
import MongoDB._
//taken from docs
val collection = connection.database("test").
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

I can't do any operation on the collection. IDE gives me: "cannot resolve symbol". Compiler gives error:

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

What is the correct way of doing it?


You are trying to call the insert operation on a Future[Collection], rather than on the underlying collection (calling operation on Future[T] rather than on T is not specific to ReactiveMongo).

It's recommanded to have a look at the documentation.