Search code examples
javascriptiosobjective-cparse-platformparse-framework

Parse iOS SDK + Cloud Code: How to update user


I am confused on how to update a user from cloud code. If someone can help me out with getting my mind right about this I'd appreciate it.

The cloud code I will use for this example is:

cloud code

Parse.Cloud.define("like", function(request, response) {
    var userID = request.params.userID;

    var User = Parse.User();
    user = new User ({ objectId: userID });

    user.increment("likes");

    Parse.Cloud.useMasterKey();
    user.save().then(function(user) {
        response.success(user);
    }, function(error) {
        response.error(error)
    });

});

called from iOS

[PFCloud callFunctionInBackground:@"like" withParameters:@{@"userID": self.selectedFriendID} block:^(id object, NSError *error) {

}];

Questions

user = new User ({ objectId: userID });

1) is the "new" in the code above creating a "brand new" user, or is it "grabbing" an existing user at the objectId so that it can be updated on user.save?

2) if the latter is correct, than is it possible to "grab" a user from a column other than the objectId column, and maybe instead grab from the userID column?

eg:

user = new User ({ userID : userID });

Solution

  • This line:

    user = new User ({ objectId: userID });
    

    Creates an instance of an object with a known ID, it only works with objectId. Any changes you make to that object are persisted, but no other data is changed (e.g. you won't accidentally blank out the other columns).

    If instead you wanted to get a user by email you would have to do a query:

    var userQuery = new Parse.Query(Parse.User);
    userQuery.equalTo('email', userEmail);
    userQuery.first().then(function(user) {
        if (user) {
            // do something with the user here
            user.set('new_col', 'new text');
            user.save().then(function() {
                response.success();
            });
        } else {
            // no match found, handle it or do response.error();
        }
    });
    
    // the above code is async, don't put anything out here and expect it to work!