Mark__C
Mark__C

Reputation: 825

Parse retrieve pointer from current user in javascript

In Parse I have the User table set up with a number of columns, most of which are Strings but one is a Pointer to another Parse Class. I want to use this pointer in a query

In Java I can access the pointer to use in my query as follows:

ParseUser currentUser = ParseUser.getCurrentUser();
ParseObject comParent = currentUser.getParseObject("ComParent");

In JavaScript I have tried using:

var currentUser = Parse.User.current();
var comParent = currentUser.get("ComParent");

But this returns undefined. What am I doing wrong?

Upvotes: 2

Views: 2625

Answers (2)

Wesley Smith
Wesley Smith

Reputation: 19571

According to the documentation:

"By default, when fetching an object, related Parse.Objects are not fetched. These objects' values cannot be retrieved until they have been fetched like so:"

var post = fetchedComment.get("parent");
post.fetch({
  success: function(post) {
    var title = post.get("title");

  }
});

So you should write:

var currentUser = Parse.User.current();
var comParent = currentUser.get("ComParent");
comParent.fetch({
    success: function(comParent) {
        var name = comParent.get("Name");
        alert(name); // this one will work
    }
});
alert(comParent.get("Name")); // this one wont work, see below

Just remember that success is an asynchronous callback,as such comParent will not be available outside the success function as shown above, if you need to access comParent outside of success check out https://stackoverflow.com/a/27673839/1376624

Upvotes: 7

Mark__C
Mark__C

Reputation: 825

Thanks. My issue was a combination of 2 things. Firstly, I was not correctly fetching the object as you rightly point out. Secondly, I was trying to fetch an object from a user which did not have an associated ComParent object (Doh!). Anyway, your solution put me onto the need to fetch the object but I don't think it is the currentUser that should have the fetch, it is comParent:

var currentUser = Parse.User.current();
var comParent = currentUser.get("ComParent");
    comParent.fetch({
        success: function(comParent) {
            var name = comParent.get("Name");
            alert(name);
        }
    });

Thanks again @DelightedD0D

Upvotes: 1

Related Questions