Unable to retrieve required object from parse.com User class using javascript - 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");

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.

Retrieve objectId in Parse

In simple, I am trying to retrieve the objectId for a particular user in parse (using Javascript). I can retrieve any other query in the database, such as username, phone, mailing address but not the objectId, here is how I retrieve the rest of the query:
var objectId = userInfo.get("objectId");
Any assistance would be greatly appreciated.
Below is more lines of the code (everything is retrieved beside objectId)
query.find({ success: function(array) {
// this means the query was a success, but we're not yet certain that we found anything
// the param to find's success is an array of PFObjects, possibly empty
if (array.length > 0) {
var userInfo = array[0];
var address = userInfo.get("address");
$scope.address = address;
var email = userInfo.get("username");
$scope.email = email;
var fullName = userInfo.get("fullName");
$scope.fullName= fullName;
var number = userInfo.get("phoneNumber");
$scope.number= number;
var objectId = userInfo.get("objectId");
$scope.objectId= objectId;
var mailingAddress = userInfo.get("mailingAddress");
$scope.mailingAddress = mailingAddress;
var plan = userInfo.get("plan");
$scope.plan = plan;
Thanks in advance
The js sdk provides an id member, so ...
$scope.objectId = userInfo.id;
As an aside, check out the JS guide on their site. It's a very well written doc. Pay particular attention to the code snippets in the objects and query sections.

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?
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

Obtain Data from two parse classes based on column in one table

I have to Parse Classes in my data browser, 'Details' and 'Content'. The 'Details' class has the following --> 'objectId', 'uuid' and 'proximity'. The 'Content' class has 'objectId', 'descId' and 'offer'.
I have created a web UI using the Javascript SDK so when the user enters the uuid, proximity and offer, uuid and proximity get stored in the 'Details' class, on success I then get the objectId of the newly created object. I then store that objectId in the 'Content' class under descId and the offer that was inputted by the user.
My problem is I have a html table that I need to populate, so I need to pull the data from both classes. The uuid and proximity from 'Details' and the offer from 'Content' so I need to do this in one query. This is my reason for storing the 'Details' objectId in the 'Content' class as a type of foreign key.
I am stuck at this cross roads and have tried include etc but I am just trying things and I'm not sure what I need to do. If anyone can help, perhaps show me a sample, I'd greatly appreciate it
Here is my js save code:
//Creating Beacon Content Parse Object
var iBeaconContent = Parse.Object.extend("Content");
var beaconContent = new iBeaconContent();
//Creating Object to save to iBeacon Description Table
var iBeaconDescription = Parse.Object.extend("Details");
var beaconDescription = new iBeaconDescription();
beaconDescription.set("uuid", tdUuid.children("input[type=text]").val().toString());
beaconDescription.set("proximity", parseInt(tdProximity.children($('prox')).val().toString()));
beaconDescription.save(null, {
success: function(beaconDescriptionObject) {
var query = new Parse.Query("Details");
query.equalTo("uuid", tdUuid.children("input[type=text]").val().toString());
query.find({
success: function(results) {
objectId = results[0].id;
beaconContent.set("descId", objectId);
beaconContent.set("offer", tdOffer.children("input[type=text]").val().toString());
beaconContent.save(null, {
success: function(object) {
document.location.reload(true);
}, error: function(beaconContent, error) {
}
});
}
});
},
error: function(error) {
}
});
NEW JAVASCRIPT
var BeaconDetail = Parse.Object.extend("Details");
var BeaconContent = Parse.Object.extend("Content");
var innerQuery = new Parse.Query(BeaconDetail);
innerQuery.exists("descId");
var query = Parse.Query(BeaconDetail);
query.matchesQuery("objectId", innerQuery);
query.find({
success:function(beaconContent){
alert("Success----lenght: " + beaconContent.length);
}
})
Sound like you need to use a compound query or relationship query. Here are some links
https://docs.parseplatform.org/js/guide/#relational-queries
https://docs.parseplatform.org/js/guide/#compound-queries
https://parse.com/questions/compound-relational-queries
An example of a query from two classes is as follows
It would also be good to see the code, would help give a more relative answer.
CODE
var lotsOfWins = new Parse.Query("Player");
lotsOfWins.greaterThan("wins", 150);
var fewWins = new Parse.Query("Player");
fewWins.lessThan("wins", 5);
var mainQuery = Parse.Query.or(lotsOfWins, fewWins);
mainQuery.find({
success: function(results) {
// results contains a list of players that either have won a lot of games or won only a few games.
},
error: function(error) {
// There was an error.
}
});
If I understand correctly, your Content class contains a pointer to your Details class in the descId property, and you want to be able to query based on some Details fields and return both objects?
NOTE: I must point out that descId is a very poorly named property that will just cause confusion. If it is a pointer, just give it a name like desc, leave off the Id suffix.
Anyway, if that is what you want:
var query = new Parse.Query("Content");
var uuid = tdUuid.children("input[type=text]").val().toString();
var proximity = parseInt(tdProximity.children($('prox')).val().toString());
// consider logging those two variable to confirm they're what you want
// query properties of a pointer
query.equalTo("descId.uuid", uuid);
query.equalTo("descId.proximity", proximity);
// include the pointer in the output
query.include("descId");
query.find({
success: function(beaconContent) {
alert("Success -- length: " + beaconContent.length);
// sample output of first result:
var content = beaconContent[0];
var detail = content.get("descId");
console.log("uuid", detail.get("uuid"));
console.log("proximity", detail.get("proximity"));
console.log("offer", content.get("offer"));
}
});

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