Search code examples
parse-platformparse-cloud-code

User object not saving in afterSave code


I have tried multiple variations of this and for some reason the field "Followers" is not being incremented:

ParseObject follow = new ParseObject("Follow");
follow.put("from", currentUser);
follow.put("to", parseUser);
follow.put("approved", approved);

Then in cloud code:

Parse.Cloud.afterSave("Follow", function(request) {
    var to = request.object.get("to");
    var query = new Parse.Query(Parse.User);
    query.equalTo("objectId", to.id);
    query.first({
        success: function(user) {
            user.increment("Followers");
            user.save();
            console.log("User: " + user.id + " Followers: " + user.get("Followers"));
        }, error: function(error) {
            console.log("afterSave: " + error);
        }
    });

    var currentUser = Parse.User.current();
    currentUser.increment("Following");
    currentUser.save();
});

According to the logs it is working:

I2015-11-28T18:21:54.745Z]v47 after_save triggered for Follow for user k0ZvNAy3Mk: Input: {"object":{"approved":false,"createdAt":"2015-11-28T18:21:54.743Z","from":{"__type":"Pointer","className":"_User","objectId":"k0ZvNAy3Mk"},"objectId":"JQBO9m21uA","to":{"__type":"Pointer","className":"_User","objectId":"bcpbFaXj9C"},"updatedAt":"2015-11-28T18:21:54.743Z"}} Result: Success I2015-11-28T18:21:54.906Z]User: bcpbFaXj9C Followers: 1

But when I look at the data the Followers field for that user still says 0

I have also tried:

Parse.Cloud.afterSave("Follow", function(request) {
    var to = request.object.get("to");
    to.increment("Followers");
    to.save();

    var currentUser = Parse.User.current();
    currentUser.increment("Following");
    currentUser.save();
});

According to the docs since it is a pointer I should be able to manipulate it directly but that did not work either.

Any ideas what to do or why this is not working correctly?


Solution

  • Looks like the parse cloud code depends on the user that is currently logged in and manipulating data on another user is not allowed unless you are logged in as them.

    Parse.Cloud.afterSave("Follow", function(request) {
        Parse.Cloud.useMasterKey(); // Needed this
    
        var to = request.object.get("to");
        to.increment("Followers");
        to.save();
    
        var currentUser = Parse.User.current();
        currentUser.increment("Following");
        currentUser.save();
    });