0

I am trying to insert data into MongoDB using Play-scala and ReactiveMongo.

Here is my DbimpService.scala:

package services
import models.Post
import reactivemongo.bson.BSONDocument
import reactivemongo.api.MongoDriver
import reactivemongo.api.collections.bson.BSONCollection
import scala.concurrent.ExecutionContext
import javax.inject.Inject
import play.api.libs.json.Json
import reactivemongo.play.json.collection.JSONCollection
import reactivemongo.api.commands.WriteResult
import scala.concurrent.Future
import org.apache.xerces.util.DatatypeMessageFormatter

class Dbimpservice @Inject() (implicit ec:ExecutionContext) extends Dbservice {
    def create(p:Post):String={
            var status = "Not Saved"
                    val driver = new MongoDriver
                    val connection = driver.connection(List("localhost"))
                    val db = connection("application")
                    val collection = db[BSONCollection]("post")
                    val futureList = collection.insert[Post](p)
                    futureList.onComplete { case sucess => println(sucess) }
            return status
    }
}

Here is my HomeController.scala:

package controllers

import javax.inject._
import play.api._
import play.api.mvc._
import models._
import scala.util.{ Failure, Success }
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
import reactivemongo.api.{ MongoDriver, MongoConnection }
import reactivemongo.play.json.collection.JSONCollection
import reactivemongo.bson.BSONDocument
import reactivemongo.api.commands.WriteResult
import reactivemongo.api.collections.bson.BSONCollection
import play.api.libs.json.Json
import services.Dbservice
import services.Dbimpservice
import services.Dbservice
import scala.concurrent.ExecutionContext
import scala.concurrent.Await
import scala.concurrent.duration.Duration

/**
 * This controller creates an `Action` to handle HTTP requests to the
 * application's home page.
 */
@Singleton
class HomeController @Inject() (implicit ec:ExecutionContext,val Dbservice : Dbimpservice)extends Controller {

    /**
     * Create an Action to render an HTML page with a welcome message.
     * The configuration in the `routes` file means that this method
     * will be called when the application receives a `GET` request with
     * a path of `/`.
     */
  def index  = Action{
    Ok("Hai")
  }

    def read = Action.async {
      val query = BSONDocument()
                    val driver = new MongoDriver
                    val connection = driver.connection(List("localhost:27017"))
                    val db = connection("application")
                    val collection = db[BSONCollection]("post")
                    val futureList = collection.find(query).cursor[Post]().collect[List]()
                    futureList.map { list =>
              Ok(list.toString())
          }
    }

    def create = Action(BodyParsers.parse.json) { request => 
     val personResult = request.body.validate[Post]
    personResult.fold(
      errors => {
        BadRequest(Json.obj("status " ->"ERROR"))
      },
      valid = fun
    )
   }

    def fun:Post => Result= { post =>
      var ans = Dbservice.create(post)
      Ok(ans)
  }

}

I am trying to insert the data but not getting inserted and the error which i am getting is

Failure(reactivemongo.core.errors.ConnectionNotInitialized: MongoError['Connection is missing metadata (like protocol version, etc.) The connection pool is probably being initialized.'])

Some one please help me, I even referred the link

http://stackoverflow.com/questions/31456517/embedmongo-with-reactivemongo-process-does-not-exit

but did not get

1
  • You need to indicate the version of the DB and of the lib Commented Jul 7, 2016 at 13:44

1 Answer 1

2

Guessing that you are using a recent version of ReactiveMongo (0.11.7+), you are using a deprecated DB resolution code (connection(dbName) aka connection.apply(dbName).

See also

You need to use the asynchronous resolution, which benefit from the failover (to handle possible network latency/incident). The following code must so be refactored.

val db = connection("application")
val collection = db[BSONCollection]("post")
val futureList = collection.insert[Post](p)

Using the new DB resolution:

for {
  db <- connection.database("application")
  collection = db("post")
  res <- collection.insert(p)
} yield res
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.