Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
184 views
in Technique[技术] by (71.8m points)

javascript - Parse cloudcode beforeSave obtain pre-updated object

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

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...