Parse Cloud Code retrieving a user with objectId

Ben picture Ben · Oct 9, 2014 · Viewed 8.8k times · Source

I am trying to get the user object from objectId. I know the objectId is valid. But I can get this simple query to work. What is wrong with it? user is still undefined after the query.

var getUserObject = function(userId){
    Parse.Cloud.useMasterKey();
    var user;
    var userQuery = new Parse.Query(Parse.User);
    userQuery.equalTo("objectId", userId);

    userQuery.first({
        success: function(userRetrieved){
            console.log('UserRetrieved is :' + userRetrieved.get("firstName"));
            user = userRetrieved;               
        }
    });
    console.log('\nUser is: '+ user+'\n');
    return user;
};

Answer

hybrdthry911 picture hybrdthry911 · Oct 11, 2014

Quick cloud code example using promises. I've got some documentation in there I hope you can follow. If you need more help let me know.

Parse.Cloud.define("getUserId", function(request, response) 
{
    //Example where an objectId is passed to a cloud function.
    var id = request.params.objectId;

    //When getUser(id) is called a promise is returned. Notice the .then this means that once the promise is fulfilled it will continue. See getUser() function below.
    getUser(id).then
    (   
        //When the promise is fulfilled function(user) fires, and now we have our USER!
        function(user)
        {
            response.success(user);
        }
        ,
        function(error)
        {
            response.error(error);
        }
    );

});

function getUser(userId)
{
    Parse.Cloud.useMasterKey();
    var userQuery = new Parse.Query(Parse.User);
    userQuery.equalTo("objectId", userId);

    //Here you aren't directly returning a user, but you are returning a function that will sometime in the future return a user. This is considered a promise.
    return userQuery.first
    ({
        success: function(userRetrieved)
        {
            //When the success method fires and you return userRetrieved you fulfill the above promise, and the userRetrieved continues up the chain.
            return userRetrieved;
        },
        error: function(error)
        {
            return error;
        }
    });
};