解析云代码之前获取预更新的对象 [英] Parse cloudcode beforeSave obtain pre-updated object

查看:179
本文介绍了解析云代码之前获取预更新的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

beforeSave 钩子中,我希望在更新之前获取对象的状态。在这种特殊情况下,它是阻止用户在完成选择后改变他们的选择。伪代码类似于:

In a beforeSave hook I want to obtain the state of the object prior to the update. In this particular case it is to stop a user from changing their choice once they have made it. Pseudo-code looks something like:

If (user has already voted) {
  deny;
} else {
  accept;
}

到目前为止我的代码是:

And the code that I have so far is:

Parse.Cloud.beforeSave('votes', function(request, response) {
  if (!request.object.isNew()) {
    // This is an update.  See if the user already voted
    if (request.object.get('choice') !== null) {
      response.error('Not allowed to change your choice once submitted');
    }
  }
  response.success();
}

request.object 是已应用更新的对象的状态。

But request.object is the state of the object with the update already applied.

请注意,'votes'对象是单独创建的,所以这不允许插入但不允许更新;我需要知道数据库中是否已经设置了给定的字段。 / p>

Note that the 'votes' object is created separately so this isn't allowing an insert but not an update will not suffice; I need to know if a given field is already set in the database.

推荐答案

请求变量是更新后的行本身。你可以得到它对象id通过 request.object.id 并使用它来抓取来自数据库的当前行并检查当前值,如下所示:

The request variable is the updated row itself. You can get it's object id through request.object.idand use this to grab the current row from the database and check the current value, like so:

Parse.Cloud.beforeSave('votes', function(request, response) {
    if (!request.object.isNew()) {
    var query = new Parse.Query("votes");
    query.get(request.object.id, { // Gets row you're trying to update
        success: function(row) {
            if (row.get('choice') !== null) 
                response.error('Not allowed to change your choice once submitted');
            response.success(); // Only after we check for error do we call success
        },
        error: function(row, error) {
            response.error(error.message);
        }
    });
}

这篇关于解析云代码之前获取预更新的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆