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

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"));
}
});

Related

Parse cloud code not working as expected with pointers (query.include)

The database has a class "Photos". This class has a pointer to "User" class.
I use this cloud code:
Parse.Cloud.define("AllPhotos", function(request, response) {
var query = new Parse.Query("Photos");
var userPointer = {"__type":"Pointer","className":"User","objectId":request.params.userId};
query.equalTo("active", true);
query.equalTo("userId", userPointer);
query.descending("createdAt");
query.include("_User");
query.find({
success: function(results) {
response.success(results);
},
error: function() {
response.error("Error 000");
}
});
});
When I query "AllPhotos" I expected to get the User object (with username, name etc) without another query but this is the result:
<Photos: 0x6080004a0240, objectId: k2SvMOVJ7s, localId: (null)> {
active = 1;
image = "<PFFile: 0x60800064cdb0>";
likes = 0;
userId = "<PFUser: 0x6080002e9300, objectId: gHfS6dzrag, localId: (null)>";
}
It just give me the objectId and I need to query again the user class to get username and name.
How can I retrieve without doing another query?
What type is userId? It looks like your userId is actually a pointer to the user? If so, you need to call query.include("userId"), not query.include("_User"). _User is the under the hood class of Parse.user. WHen you use include, you need to include the field name a pointer is stored under.

Basic Parse query to access a field inside a pointer object in JavaScript

I have a table called "Current1", which I am saving user's object as pointer like this:
When I click on this pointer I direct to _User table. Now I am trying to do very simple query. I need to access to username inside user pointer and later update something in _User table.
My problem is now to access 'username' in '_User' table by using a pointer:
var aveGame2 = Parse.Object.extend("Current1");
var query2 = new Parse.Query(aveGame2);
query2.include("user");
query2.find({
success: function(results) {
for (var i = 0; i < results.length; i++)
{
var object = results[i];
//....
var user = object.get('user');
var username = user.get('username'); //<--Error is pointing to this line
//More operation
if(True)//Some conditions
{
Parse.Cloud.useMasterKey();
var query = new Parse.Query(Parse.User);
query.equalTo("username", username);
// Get the first user which matches the above constraints.
query.first({
success: function(anotherUser) {
anotherUser.set("prize", 10);
// Save the user.
anotherUser.save(null, {
success: function(anotherUser) {
// The user was saved successfully.
response.success("Successfully updated user.");
},
error: function(gameScore, error) {
// The save failed.
// error is a Parse.Error with an error code and description.
response.error("Could not save changes to user.");
}
});
},
error: function(error) {
response.error("Could not find user.");
}
});
Error:
[Error]: TypeError: Cannot call method 'get' of undefined
at e.query2.find.success
After hours of checking each fields I realised I have not set ACL for _User table as Public read. This might help someone else.

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.

parse.com : Inner query on an id column Not retrieving all columns I want

Parse class Schema :
Class name : balance
Columns : myid createdAt amount
Class name : tokens
Columns : myid registerUser isActiveToken
I want to retrieve amount, myid, registerUser, isActiveToken using parse.com javascript.
I am not able to get this using parse js refernce.
https://parse.com/docs/js/guide#queries
matchesKeyInQuery is giving a toJSOn error in parse js
var balance = Parse.Object.extend("balance");
var teamQuery = new Parse.Query(balance);
var userQuery = new Parse.Query("tokens");
userQuery.matchesKeyInQuery("amount", teamQuery); //I made a blunder here by not understanding matchesKeyInQuery
userQuery.find({
success: function(results) {
// results has the list of users with a hometown team with a winning record
}
});
matchesQuery is throwing a bad inner query error
var balance = Parse.Object.extend("balance");
var tokens = Parse.Object.extend("tokens");
var innerQuery = new Parse.Query(balance);
innerQuery.exists("amount");
var query = new Parse.Query(tokens);
query.matchesQuery("myid", innerQuery);
query.find({
success: function(comments) {
// tokens now contains the tokens for balance with amounts.
}
});
Overcame this through javascript merging(dirty way), would love to find something in Parse SDK
in the first query method matchesKeyInQuery accepts 3 arguments, first one is the key in the called query, the second one argument is the key in the passed query and third one is the passed query.
var balance = Parse.Object.extend("balance");
var tokens = Parse.Object.extend("tokens");
var teamQuery = new Parse.Query(balance);
var userQuery = new Parse.Query(tokens);
userQuery.equalTo("myId",12); //sample
userQuery.matchesKeyInQuery("myId","myId", teamQuery);
userQuery.find({
success: function(results) {
// results has the list of users with a hometown team with a winning record
}
});
for the second query, you should have relation between two collections . and you can use matchesQuery method.

Parse cloud code relations query

I'm trying to query whether a PFUser exists in another PFUser's 'blockedUsers' relation column before sending a push notification:
I have written this but it doesn't seem to be working:
var recipientBlockList = toUser.relation("blockedUsers");
var blockListQuery = Parse.Query(recipientBlockList);
blockListQuery.contains(fromUser);
blockListQuery.find({
success: function(users) {
},
error: function() {
}
});
For relation object queries, you should use yourRelation.query():
var blockListQuery = recipientBlockList.query();

Categories

Resources