我很困惑如何有条件地更新基于以前的查询的文档,只使用期货。
假设只有当数组的大小小于给定的整数时,我才想将该值推入文档中的数组中。
我使用这个函数来获取文档,在得到文档之后,我正在推送值--我不能做的就是有条件地这样做。
def joinGroup(actionRequest: GroupRequests.GroupActionRequest): Future[GroupResponse.GroupActionCompleted] = {
//groupisNotFull() is a boolean future
groupIsNotFull(actionRequest.groupId).map(
shouldUpdate => {
if(shouldUpdate){
Logger.info(actionRequest.initiator + " Joining Group: " + actionRequest.groupId)
val selector = BSONDocument("group.groupid" -> BSONDocument("$eq" -> actionRequest.groupId))
val modifier = BSONDocument("$push" -> BSONDocument("group.users" -> "test-user"))
val updateResult = activeGroups.flatMap(_.update(selector, modifier))
.map(res => {
GroupActionCompleted(
actionRequest.groupId,
actionRequest.initiator,
GroupConstants.Actions.JOIN,
res.ok,
GroupConstants.Messages.JOIN_SUCCESS
)
})
.recover {
case e: Throwable => GroupActionCompleted(
actionRequest.groupId,
actionRequest.initiator, GroupConstants.Actions.JOIN,
success = false,
GroupConstants.Messages.JOIN_FAIL
)
}
updateResult
}
else {
val updateResult = Future.successful(
GroupActionCompleted(
actionRequest.groupId,
actionRequest.initiator,
GroupConstants.Actions.JOIN,
success = false,
GroupConstants.Messages.JOIN_FAIL
))
updateResult
}
}
)
}
//returns a Future[Boolean] based on if there is room for another user.
private def groupIsNotFull(groupid: String): Future[Boolean] = {
findGroupByGroupId(groupid)
.map(group => {
if (group.isDefined) {
val fGroup = group.get
fGroup.group.users.size < fGroup.group.groupInformation.maxUsers
} else {
false
}
})}
我不明白为什么我不能这样做。编译错误是:
错误:类型错配;找到: scala.concurrent.Futureresponse.group.GroupResponse.GroupActionCompleted必需: response.group.GroupResponse.GroupActionCompleted
用于if分支和else分支“updateResult”。
作为一个附带问题..。这是否是有条件地更新文档的正确方式--即查询文档,执行一些逻辑,然后执行另一个查询?
发布于 2017-06-23 14:40:33
好的,明白了-您需要像这样flatMap第一个Future[Boolean]:
groupIsNotFull(actionRequest.groupId).flatMap( ...使用flatMap,结果将是一个带有map的FutureT,您将得到一个Future[FutureT]。编译器知道您想返回一个FutureT,所以它期望映射返回一个T,并且您正在尝试返回一个FutureT,所以它会抛出错误。使用flatMap可以解决这个问题。
地图与平面图的进一步清晰性:In Scala Akka futures, what is the difference between map and flatMap?
发布于 2017-06-22 20:57:21
我认为问题在于,因为joinGroup2函数返回类型是FutureResponse,但是您只返回了else块中的一个响应。如果查看mapToT函数的签名,它将返回一个FutureT。
我认为您需要在“未来”中包装响应对象。就像这样:
else {
Future { Response(false, ERROR_REASON) }
}顺便说一句,您有一个错误:响应->响应
https://stackoverflow.com/questions/44707867
复制相似问题