Parse object not editing successfully - javascript

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

Related

Add two values in dictionary parse cloud code

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.

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 Cloud Code save() doesn't seem to save a field

I'm trying to run save() on a retrieved _User object, but it doesn't seems to save the field I've modified ("ignoredUsers"), which is an array. Although I can see that the save actually went through, as updatedAt does change.
Here is the code:
var query = new Parse.Query(Parse.User);
query.equalTo("objectId", userid1);
query.first({
success: function(result){
var ignored = result.get("ignoredUsers");
if (!ignored) {
ignored = [];
}
ignored.push(userid2);
result.set("ignoredUsers", ignored);
result.save();
}
});
function appendUser(toUser, userId) {
return toUser.fetch({
success: function(user) {
var ignored = user.get("ignoredUsers");
if (!ignored) {
ignored = [];
}
ignored.push(userId);
user.set("ignoredUsers", ignored);
user.save();
}
});
}
Parse.Cloud.job("ignoredUsers", function(request, status) {
Parse.Cloud.useMasterKey();
var query = new Parse.Query("Conversation");
return query.each(function(conversation) {
var participants = conversation.get("participants");
var userid1 = participants[0].id;
var userid2 = participants[1].id;
var user1 = participants[0];
var user2 = participants[1];
return appendUser(user1, userid2).then(function() {
return appendUser(user2, userid1); });
});
status.success();
});
The problem was that the cloud function returned before waiting for the callbacks to finish

Categories

Resources