Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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();
}

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
178 views
Welcome To Ask or Share your Answers For Others

1 Answer

While Krodmannix's response is correct (and was helpful to me) it has the overhead of a full query. If you are doing things in beforeSave, you really want to streamline them. As a result, I believe a fetch command is much preferable.

Parse.Cloud.beforeSave('votes', function(request, response) {
    if (!request.object.isNew()) {
      var Votes = Parse.Object.extend("votes");
      var oldVote = new Votes();
      oldVote.set("objectId",request.object.id);
      oldVote.fetch({
        success: function(oldVote) {
            if (oldVote('choice') !== null) {
                response.error('Not allowed to change your choice once submitted');
            }
            else {
                response.success(); // Only after we check for error do we call success
            }
        },
        error: function(oldVote, error) {
            response.error(error.message);
        }
    });
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...