Parse cloud code relations query - javascript

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();

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.

Parse Cloud Code - Only Retrieve Certain Columns Before Sending Response.

I currently have this cloud code to retrieve all the users that have a relation with the current user. I have to first find the current user then query the "Friends" column hence the relational query step.
The line response.success(results) returns all the attributes of all of the current user's friends. I only want a few of the columns that belong to these friends, not every single thing they saved when signing up.
Parse.Cloud.define("getFriends", function(request, response) {
var userId = request.params.UserKey;
var query = new Parse.Query(Parse.User);
query.ascending("updatedAt");
query.get(userId, {
success: function(foundCurrentUser) {
var currentUser = foundCurrentUser;
var relation = currentUser.relation("Friends");
var getRelationQuery = relation.query();
getRelationQuery.find().then(function(results) {
response.success(results);
});
},
error: function(error) {
response.error(error);
}
});
});
I am using swift to to use the response, I am not sure that if I need to tweak the swift code but will provide it anyway.
func LoadCarpoolersFromParse(Success:(object:AnyObject)->(),Failure:(error:NSError)->())
{
let params = NSMutableDictionary()
params.setObject(PFUser.currentUser()!.objectId!, forKey: "UserKey")
PFCloud.callFunctionInBackground("getCarpoolers", withParameters: params as [NSObject : AnyObject], block: {
(response:AnyObject?, error: NSError?) -> Void in
if error == nil {
Success(object: response!)
}
else{
Failure(error:error!)
}
})
}
}
You can do it by using select method of Parse.Query, make the following changes in your cloud code
Parse.Cloud.define("getFriends", function(request, response) {
var userId = request.params.UserKey;
var query = new Parse.Query(Parse.User);
query.ascending("updatedAt");
query.select("name","phone"); // replace with your required fields

How can I retrieve a list of objects from a class relation?

I have a class Store that has a relation itemsInStore that contains multiple Item objects on Parse. I'm currently trying to Parse Cloud Code to retrieve all Items in a Store, but don't know what a common practice for this is.
In particular, I couldn't find articles that really answer my question here, e.g. how the query should be.
Parse.Cloud.define("retrieveNearbyLocationsAndItemsWithCurrentLocation", function(request, response) {
var Store = Parse.Object.extend("Store");
var store = new Store();
var query = new Parse.Query(Store);
var userGeoPoint = new Parse.GeoPoint(request.params.lat, request.params.long);
query.near("geopoint", userGeoPoint);
query.limit(1);
query.find({
success: function(httpResponse) {
response.success(httpResponse[0].get("itemsInStore"));
console.log(httpResponse[0].get("itemsInStore"));
},
error: function(httpResponse) {
response.error("Error: retrieveNearbyLocationsAndItemsWithCurrentLocation");
}
});
});
Console log would return {"__type":"Relation","className":"Item"}
In order to dig into this Relation and retrieve all Item objects in it, what should be done next?
The relation answers a query. Run that query to get the related elements.
Parse.Cloud.define("retrieveNearbyLocationsAndItemsWithCurrentLocation", function(request, response) {
var Store = Parse.Object.extend("Store");
var store = new Store();
var query = new Parse.Query(Store);
var userGeoPoint = new Parse.GeoPoint(request.params.lat, request.params.long);
query.near("geopoint", userGeoPoint);
query.limit(1);
query.find().then(function(stores) {
if (stores.length && stores[0].relation("itemsInStore")) {
var itemQuery = stores[0].relation("itemsInStore").query();
return itemQuery.find();
} else {
return [];
}
}).then(function(items) {
response.success(items);
}, function(error) {
response.error(error);
});
});

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

Categories

Resources