Add two values in dictionary parse cloud code - javascript

I have to use the masterkey to write to another user to store values in a column in the parse class. The column holds a dictionary, where the first value is a id var chatDialogId = request.params.chatID; and the second value is 0 or 1.
When the value is first being created is when the object created we set the second value to 1.
I get the id for the first value from the request.
Parse.Cloud.define("addFriendToFriendsRelation", function(request, response) {
var friendRequestId = request.params.Friends;
var chatDialogId = request.params.chatID;
var query = new Parse.Query(Parse.User);
query.get(friendRequestId, {
useMasterKey: true,
success: function(friendRequest) {
var fromUser = friendRequest;
var toUser = request.user;
var relation = fromUser.relation("Friends");
// notification is the dictionary column...
var notification = fromUser.get("notification");
//WHICH WAY???
//notification.push????
//notification.put?????
relation.add(toUser);
fromUser.save(null, {
useMasterKey: true,
success: function() {
response.success("saved relation and updated friendRequest");
},
error: function(error) {
response.error(error);
}
});
},
error: function(error) {
response.error(error);
}
});
});
The fromUser is the user we found from the user query and where we want to update the notification dictionary.

Related

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

Taking data from a javascript object queried from parse.com

I have a parse.com database which i am querying using the objectID. It returns the data but I can only see it inside the promise object as an attribute, i can't figure out how this works from the documentation, how should i actually get the data and turn it into an object rather than a Promise. Should i call the function after or save it as a variable or something in the success function, do i need to define review somewhere earlier? any example would be awesome
var query = new Parse.Query("business_and_reviews");
var results = new Parse.Object("business_and_reviews");
query.get("pLaARFh2gD", {
success: function(results) {
// results is an array of Parse.Object.
},
error: function(object, error) {
// The object was not retrieved successfully.
// error is a Parse.Error with an error code and message.
}
});
var name = results.get("city");
console.log(name);
This is the Promise in chrome
get() returns only one object with the id.
var query = new Parse.Query("business_and_reviews");
query.get("pLaARFh2gD", {
success: function(result) {
var name = result.get("city");
console.log(name);
}
});
Here is another example from the document.
var GameScore = Parse.Object.extend("GameScore");
var query = new Parse.Query(GameScore);
query.get("xWMyZ4YEGZ", {
success: function(gameScore) {
var score = gameScore.get("score");
var playerName = gameScore.get("playerName");
var cheatMode = gameScore.get("cheatMode");
},
error: function(object, error) {
// The object was not retrieved successfully.
// error is a Parse.Error with an error code and message.
}
});
Thanks, I solved it now, first had to be inside the success: function, then had to select the info in the object as follows:
var query = new Parse.Query("business_and_reviews");
var results = new Parse.Object("business_and_reviews");
query.get("pLaARFh2gD", {
success: function(results) {
console.log(results["attributes"]["city"]);
},
error: function(object, error) {
}
});

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

Parse object not editing successfully

I'm writing a function that queries Parse for a matchCenterItem object associated with the respective user, and then editing certain properties of that object. When the query is made, the response (results) is returned in this form:
<matchCenterItem: 0x7f84e2c1a4b0, objectId: Je1VxP7dPw, localId: (null)> {
categoryId = 9355;
itemCondition = Used;
itemLocation = US;
maxPrice = 350;
minPrice = 250;
parent = "<PFUser: 0x7f84e2c20c10, objectId: kfEHfG4FUD>";
searchTerm = "iphone 5 unlocked";
}
I then want to update the fields with the params being sent. When the function is run, it prints out 'MatchCenterItem successfully edited!', and yet when I check the dashboard, the item hasn't been updated at all. Am I missing something? Full code is below.
Parse.Cloud.define("editMatchCenter", function(request, response) {
var matchCenterItem = Parse.Object.extend("matchCenterItem");
var query = new Parse.Query(matchCenterItem);
query.contains('searchTerm', request.params.searchTerm);
query.equalTo('parent', Parse.User.current())
query.first().then(function(results) {
results.set('minPrice', request.params.minPrice);
results.set('maxPrice', request.params.maxPrice);
results.set('itemCondition', request.params.itemCondition);
results.set('itemLocation', request.params.itemLocation);
results.save();
});
response.success('MatchCenterItem successfully edited!');
});
Changed the code to this and it works now:
Parse.Cloud.define("editMatchCenter", function(request, response) {
var matchCenterItem = Parse.Object.extend("matchCenterItem");
var query = new Parse.Query(matchCenterItem);
query.contains('searchTerm', request.params.searchTerm);
query.equalTo('parent', Parse.User.current())
query.first({
success: function(results) {
results.set('minPrice', request.params.minPrice);
results.set('maxPrice', request.params.maxPrice);
results.set('itemCondition', request.params.itemCondition);
results.set('itemLocation', request.params.itemLocation);
results.save();
response.success('MatchCenterItem successfully edited!');
},
error: function() {
response.error('MatchCenterItem NAAAAT successfully edited!');
}
});
});

Categories

Resources