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

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

问题描述

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' 对象是单独创建的,因此这不允许插入但不允许更新是不够的;我需要知道数据库中是否已经设置了给定的字段.

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.

推荐答案

request 变量是更新后的行本身.您可以通过 request.object.id 获取它的对象 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);
        }
    });
}

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

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