Parse retrieve pointer from current user in javascript - 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?

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

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

Related

Cannot create a pointer to an unsaved ParseObject

I am having troubles referring to a "User" object from inside a query. I have the following code:
Parse.Cloud.define("getTabsBadges", function(request, response) {
var UserObject = Parse.Object.extend('User');
var user = new UserObject();
user.id = request.params.userId;
// Count all the locked messages sent to the user
var receivedMessagesQuery = new Parse.Query('Message');
receivedMessagesQuery.equalTo('status', 'L');
receivedMessagesQuery.equalTo('toUser', user); // THIS LINE GENERATES THE ERROR
receivedMessagesQuery.count({
// more code here
});
});
I call the function using CURL but I always get the following error:
{"code":141,"error":"Error: Cannot create a pointer to an unsaved
ParseObject\n at n.value (Parse.js:14:4389)\n at n
(Parse.js:16:1219)\n at r.default (Parse.js:16:2422)\n at e.a.value
(Parse.js:15:1931)\n at main.js:9:25"}
I am using the exactly same code in another project, the only difference is that instead of counting objects I find them and its works correctly. I have also verified that the tables have a column type of Pointer<_User> in both projects. What's causing the problem?
The error message Cannot create a pointer to an unsaved means that you are trying to use an object which does not exist in the Parse DB.
With var user = new UserObject();, you're creating a new user object. You cannot use it in a query until you save it to Parse.
Instead of creating a new User object and setting it's objectId, do a query for the User object. See code below:
Parse.Cloud.define("getTabsBadges", function(request, response) {
var UserObject = Parse.Object.extend('User');
var query = new Parse.Query(UserObject);
query.get(request.params.userId, {
success: function(user) {
// Count all the locked messages sent to the user
var receivedMessagesQuery = new Parse.Query('Message');
receivedMessagesQuery.equalTo('status', 'L');
receivedMessagesQuery.equalTo('toUser', user); // THIS LINE GENERATES THE ERROR
receivedMessagesQuery.count({
// more code here
});
},
error: function(error) {
// error fetching your user object
}
});
});
Your request.params.userId may be undefined or null, which causes this error.
Your query constraints cannot compare the Parse Object that is created without data (createWithoutData()) using undefined or null as its objectId.

How to access property of json object from restful web service

I need to access the name property of the user object that is returned by a restful web service, so far I can see the object being returned, but I do not know how to access the name property and assign it to a variable
User.get.then(function (payload) {
var usrname = '';
var usrobj = angular.fromJson(payload.data);
});
Can someone please show me how can I assign the property name value, to the variable usrname?
Thank you.
is the name attribute in the first level of the object? if yes:
User.get.then(function (payload) {
var usrname;
var usrobj = angular.fromJson(payload.data);
usrname = usrobj.name;
});

Cloud Code add attribute to response

I need to modify / add an attribute to a Parse object before returning it, but not save it to the database.
Here's my scenario:
I do a query for a single record and when successful, I need to add a field to that object:
...
query.first({
success: function(result) {
// get current and expiration date and calculate expiration
var now = new Date();
var expiresInHours = moment(results.get("expiresAt")).diff(now, 'hours');
// set attribute
result.add("expiration", expiresInHours);
// respond to client
response.success(result);
The problem is that I always get an error, because I modified an object and didn't save it.
I would really like to return just the object instead of having to create a new object like
var answer = {"data": result, "expiration": expiresInHours};
which would work, but then I would need to change a lot of code on the client side....
Any help? Thx,
Martin.
On using the "set" method for the object, it will try to save the object where that particular column will not be there so try converting the result to a JSON and try inserting attr to the objects.
var resultsJson = [];
for (var i = 0; i<results.length; i++) {
var resultJson = (results[i].toJSON());
if (relations[results[i].get("user").id] != null) {
resultJson["relationship"] = someValue;
}
resultsJson.push(resultJson);
}
response.success(resultsJson);`

Unable to retrieve required object from parse.com User class using javascript

I'm using the JavaScript SDK with I'm using parse.com.
The below code is meant to select the user thats currently logged in, then retrieve their "username" from the "User" class and show it in the console log.
Parse.initialize("XXXX", "XXXX");
var currentUser = Parse.User.current();
var query = new Parse.Query(Parse.User);
query.equalTo(currentUser);
query.find({
success: function(theuser) {
console.log(username);
}
});
UPDATE, BASED ON THE ANSWER BELOW I TRIED
var currentUser = Parse.User.current();
var user = currentUser.get("username");
var user = currentUser.get("gender");
console.log(user);
console.log(gender);
but now get Uncaught ReferenceError: gender is not defined ?
At the moment I'm getting the following error.
POST https://api.parse.com/1/classes/_User 400 (Bad Request)
parse-1.2.17.min.js:1 t._ajax parse-1.2.17.min.js:1 t._request
parse-1.2.17.min.js:1 t.Query.find parse-1.2.17.min.js:3 (anonymous
function)
This seems to say it cannot find the User class, but you can see from the screen shot this does exist. Can anyone help me with what the issue is here?
With "var currentUser = Parse.User.current(); " you already have the current user object. Don't query for it. Just get the value from the object.
One problem is here:
var user = currentUser.get("username");
var user = currentUser.get("gender"); //you also named this var 'user' instead of 'gender'
change this to:
var user = currentUser.get("username");
var gender = currentUser.get("gender");

Parse.com unable to get username from Parse.User.current?

Using javascript, after the user logs in successfully, I tried to extract the username as below:
var user = Parse.User.current();
name = user.getUsername;
The value of name is: function (){return this.get("username")}
If I use name = user.getUsername();
The value is undefined!!
user.fetch().then(function(fetchedUser){
var name = fetchedUser.getUsername();
}, function(error){
//Handle the error
});
Here the issue is Parse.User.current() method will return a user object if the user logged in or signed up successfully, but this object wont be having all the details of the user object. In order to get all the object properties you have to call fetch method on a user Object.
try
var user = Parse.User.current();
var name= user.get("username");

Categories

Resources