【问题标题】:Updating other objects in cloud code from same table parse.com从同一个表 parse.com 更新云代码中的其他对象
【发布时间】:2016-08-10 12:28:29
【问题描述】:

我试图完成的事情:

  • 用户可以将位置保存到表中,并将它们置于活动/非活动状态。

餐桌位置:

  • user(指向用户的指针)
  • 位置(地理数据)
  • 活动(布尔)

场景:

  • 用户保存一个新位置,它会自动将该位置设置为 积极的。其他的都应该设置为非活动状态。
  • 用户将保存的位置设置为活动,自动将所有其他位置 应设置为非活动。

所以最终在位置表中,一个用户可以有多个位置,但同时只能有 1 个处于活动状态。 我认为这是 cloudcode 的完美之选

我和之前一样把这个放到cloudcode中保存:

Parse.Cloud.beforeSave("Location", function(request, response) {
    var query = new Parse.Query("Location");
    query.equalTo("user", request.object.get("user"));
    query.equalTo("active", true);
    query.find({
    success: function(results) {
      //get all objects in the table and set the active property to false
      for (var i = 0; i < results.length; i++) {
            var object = results[i];
             object.set('active',false);
             object.save();
      }
      response.success();
    },
    error: function(error) {
      response.error(error.message);
    }
  });
}
});

猜猜会发生什么...所有对象都设置为 false,我想我知道为什么...因为当您在 cloudcode 中保存对象时,它会在再次保存挂钩之前调用解析云,对吗?

对此我能做些什么还是我的逻辑错了?

【问题讨论】:

  • @cricket_007 错字:)
  • 好的,所以这不起作用?您要发送活动位置吗?如果没有,您可以设置时间戳并使用后保存功能将最近的位置设置为活动
  • @cricket_007 嗯,我真的不明白你在说什么......因为你仍然会处于循环中
  • 如果您一次应该只有一个活动位置,为什么还需要循环?
  • 如果你只有一个活动位置,你不需要查询所有你可以用 first() 替换 find() 因为你知道你只有一个活动位置

标签: parse-platform parse-cloud-code


【解决方案1】:

我提出这个解决方案:

Parse.Cloud.beforeSave("Location", function(request, response) {

   var location = request.object;
   if (location.get("active")){
        var query = new Parse.Query("Location");
        query.equalTo("user", request.object.get("user"));
        query.equalTo("active", true);

        query.first().then(function(result){
                results.set('active',false);
               results.save()
            .then(function(){
                response.success();
            });
         },function (error) {
            response.error(error.message);
         });
   } else {
        response.success();
   }
});

因此,当您保存“inActive”位置时,beforeSave 响应正常。如果您保存一个新的活动位置,它将首先检查唯一的活动位置 (query.first) 并将其设置为非活动(这样 beforeSave 将成功),然后您保存新的活动位置。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-26
    • 2015-08-08
    • 2016-05-04
    • 1970-01-01
    相关资源
    最近更新 更多