【问题标题】:Perform 2 operations to update on ReactiveMongo在 ReactiveMongo 上执行 2 次更新操作
【发布时间】:2016-04-12 19:27:59
【问题描述】:

我正在测试 mongo shell 上的下 2 个查询,它可以工作,

但现在,我需要在 reactivemongo 中执行相同的查询

有人可以给我一个关于如何在响应式mongo中进行查询的建议

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

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

有没有更好的方法来运行这个查询?

【问题讨论】:

  • 不确定您的意思。您想从一个集合中检索一个文档并将其推送到另一个文档的数组属性中吗?您想要“整个”文档还是只想要_id?此外,您的$push 语句正在创建一个“单元素数组” 另一个"presell" 数组中。所以它看起来像"presell": [[{ "_id": { document } }]]。你的意思可能是{ "$push": { "presell": { "_id": doc } } } 甚至{ "$push": { "presell": { "_id": doc._id } } } 或者只是{ "$push": { "presell": doc } }。很难说出你在这里的真正意思。
  • 此外,除非您在一个框架上执行“自动转换”,因为定义“类型”的文档定义了“模式”,否则您的意思可能是 "_id": ObjectId("5704441ea356f55ab590e8f4"),除非数据被弄乱并且您以某种方式将ObjectId 值存储为“字符串”。
  • 你试过什么?你仔细阅读documentation了吗?

标签: mongodb scala reactivemongo play-reactivemongo


【解决方案1】:

使用 flatMap 是我一直在寻找的解决方案

  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

【讨论】:

    猜你喜欢
    • 2014-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多