问题
I'm having trouble getting my aftersave cloud function to increment a value in another data table. The Parse documentation is a bit confusing on this front.
I have a table called "CandidateVotes" that stores a row for each vote on a "candidate" - and when a new vote row is saved, I would like to increment the total votes count stored in a different table called "CategoryCandidates" which has a row for each "candidate".
So the relevant information:
- Votes table is called "CandidateVotes"
- Candidates table is called "CategoryCandidates"
- Total votes count column in CategoryCandidates table is called "votes"
Here's my Parse aftersave cloud function:
Parse.Cloud.afterSave("CandidateVotes", function(request) {
query = new Parse.Query("CategoryCandidates");
query.get(request.object.get("CategoryCandidates").objectID, {
success: function(candidate) {
candidate.increment("votes");
candidate.save();
},
error: function(error) {
console.error("Got an error" + error.code + " : " + error.message);
}
});
});
When a new vote is saved, this is the error that I'm getting in my cloud code logs:
E2015-09-04T15:49:23.553Z]v9 after_save triggered for CandidateVotes as master:
Input: {"object":{"candidateID":{"__type":"Pointer","className":"CategoryCandidates","objectId":"HOBbNA690z"},"createdAt":"2015-09-04T15:49:09.216Z","objectId":"RlmvJjG04t","updatedAt":"2015-09-04T15:49:23.549Z","userID":{"__type":"Pointer","className":"_User","objectId":"7YfU2ETvb3"}}}
Result: TypeError: Cannot read property 'objectID' of undefined
at main.js:6:53
The Parse documentation (https://parse.com/docs/js/guide#cloud-code-aftersave-triggers) has an example, but it's unclear to me what the lowercase "post" is referring to in their data schema. I'm also not well-versed in JS so might be making a rookie mistake there.
Thanks in advance for any suggestions or advice!
回答1:
It can definitely be a bit of a head-scratcher to debug cloud code but you were nearly there. You want to access the objectId of the "CategoryCandidates" class pointer, which you are currently using request.object.get("CategoryCandidates").objectID
to do.
The problem is, when you look at the log for the input to your afterSave, the name of the pointer is "candidateID", not "CategoryCandidates".
Try using request.object.get("candidateID").objectID
Cheers, Russell
来源:https://stackoverflow.com/questions/32405297/aftersave-cloud-function-for-parse-that-increments-value-in-another-data-table