0

I am testing the next 2 query on mongo shell an it works,

But now, I need to perform the same query in reactivemongo

Someone can give me a suggestion for how to make the query in reactivemongo

doc = db.offer.find({"_id": "5704441ea356f55ab590e8f4"})

db.student.update(
  { "_id" : "570681b30fc032dea831c132"},
  { $push: { 
    "presell": [
        { "_id" : doc }
      ]
    } 
  }
)

is there a better way to run this query?

cchantep
  • 9,118
  • 3
  • 30
  • 41
Sanx
  • 223
  • 1
  • 6
  • 17
  • Not sure what you mean here. You want to retrieve a document from one collection and push it into the array property of another document? Do you want the "whole" document or just the `_id`? Also your `$push` statement is creating a "single element array" **within** another array of `"presell"`. So it would look like `"presell": [[{ "_id": { document } }]]`. You probably mean `{ "$push": { "presell": { "_id": doc } } }` or even `{ "$push": { "presell": { "_id": doc._id } } }` or just `{ "$push": { "presell": doc } }`. Hard to tell what you really mean here. – Neil Lunn Apr 08 '16 at 00:41
  • Also unless you are on a framework that does "autocasting" due to s defined "schema" for the documents that defines "types", you likely mean `"_id": ObjectId("5704441ea356f55ab590e8f4")` unless the data is messed up and you have somehow stored `ObjectId` values as "strings". – Neil Lunn Apr 08 '16 at 00:44
  • What have you tried? Do you have carefully read the [documentation](http://reactivemongo.org/releases/0.11/documentation/tutorial/find-documents.html)? – cchantep Apr 08 '16 at 07:22

1 Answers1

0

the use of flatMap was the solution I was looking for

  def preSell( user_id: String, offer_id: String ) = Action.async {

    val futureResults = collection_offer.find( Json.obj("_id" -> offer_id ) ).one[JsValue]
    futureResults.flatMap {
      case Some(document) => 

        val futureUpdate = collection.update( Json.obj( "_id" -> user_id ), Json.obj( "$addToSet" -> Json.obj( "presell" ->  Json.toJson(document) ) ) )

        futureUpdate.map { result =>
          Logger.debug("Successfully update")
          Ok( Json.obj( data -> Json.obj( "_id" -> user_id ) ) )
        }.recover {
          case t: TimeoutException =>
            Logger.error("Problem found in student update process")
            InternalServerError(t.getMessage)
        }

      case None => 
        Future.successful( Ok( Json.obj( data -> "Document NotFound" ) ) )
    }.recover {
      case t: TimeoutException =>
        Logger.error("Problem obtaining teacher")
        InternalServerError(t.getMessage)
    }

  }

Scala Play Action.async cant resolve Ok as mvc.AnyContent

Community
  • 1
  • 1
Sanx
  • 223
  • 1
  • 6
  • 17