Deleting object from array in Parse Cloud Code (Javascript) - javascript

Below is my JS code that is supposed to delete a pointer reference to a 'Game' object which is stored in an array under the key 'games' in the 'team' object. Fetching works and all the 'success' logs below get called meaning that the .remove and .save functions get called, but for some reason, this does not do anything and the pointers still exist in the arrays after the execution of this code.
What am I doing wrong?
var queryTeam = request.object.get("awayTeamID");
queryTeam.fetch({
success: function(awayTeam){
console.log("Success in Fetching awayTeam Object. Destroying Now.");
awayTeam.remove(awayTeam.get("games"), request.object);
awayTeam.save();
var queryTeam = request.object.get("homeTeamID");
queryTeam.fetch({
success: function(homeTeam){
console.log("Success in Fetching homeTeam Object. Destroying Now.");
homeTeam.remove(homeTeam.get("games"), request.object);
homeTeam.save();
},
error: function(homeTeam, error){
console.error("Error removing game from homeTeam array! " + error.code + ": " + error.message);
}
});
},
error: function(myObject, error){
console.error("Error removing game from awayTeam array! " + error.code + ": " + error.message);
}
});

Your approach to removing is incorrect, you don't need to fetch the array to remove it, the remove request should be made on the object:
awayTeam.remove("games", request.object);

Related

Retrieving values of objects in a parse database

So I'm trying to pull the name of the creator, just for testing purposes, from the session object. The creator object is a pointer but it keeps coming up as undefined however? Any clue why?
function joinLobby(){
var ses = Parse.Object.extend("Session");
var query = new Parse.Query(ses);
query.equalTo("Name", document.getElementById("lobby").value);
query.find({
success: function(results) {
console.log("Successfully retrieved " + results.length );
// Do something with the returned Parse.Object values
session = results[0];
addPlayer(session,player);
console.log("session joined: "+session.get("Name"));
console.log("The creator is: "+session.get("Creator").get("Name")); // coming up as undefined
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
}
This is because the query does not load the object pointed by the pointer. To do that you need to add this extra line and then run your query.
query.include("Creator");

Parse.com / Javascript - Save users objectid string as user pointer

How do I save a user pointer to an object when i have the object id of the user.
I am able to save the object to the class in Parse but the assignee is always 'Undefined' in Parse.
e.g. I have retrieved the user object and can get the username / object id etc through:
function getUserFromUsername(username) {
Parse.initialize("...", "...");
console.log('The username passed in is: ' + username);
var User = Parse.Object.extend("_User");
var query = new Parse.Query(User);
query.equalTo("username", username);
query.first({
success : function(result) {
// Do something with the returned Parse.Object values
var userPointer = new Parse.User();
userPointer = result;
console.log(userPointer.get('username')); // this returns the correct username
return userPointer;
},
error : function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
}
Which is called from my save task function below: (Note, I've logged all relevant fields and they return as expected.
function saveNewTask(clientName, taskTitle, taskDue, assigneeArray) {
Parse.initialize("...", "...");
var x;
for (x in assigneeArray) {
var Task = Parse.Object.extend("Tasks");
var task = new Task();
task.set("title", taskTitle);
task.set("date", taskDue);
var thisAssignee = GetUserFromUsername(assigneeArray[x]);
task.set('assignee', thisAssignee);
task.save(null, {
success : function(task) {
// Execute any logic that should take place after the object is saved.
console.log('New object created with objectId: ' + task.id);
},
error : function(gameScore, error) {
// Execute any logic that should take place if the save fails.
// error is a Parse.Error with an error code and message.
console.log('Failed to create new object, with error code: ' + error.message);
}
});
}
}
So you should save a pointer to the user to the task.
var Task = Parse.Object.extend("Tasks");
var task = new Task();
task.set("user", user);
task.set("title", "taskTitle");
task.set("date", taskDue);
task.save(null, {
success : function(task) {
// Execute any logic that should take place after the object is saved.
console.log('New object created with objectId: ' + task.id);
},
error : function(gameScore, error) {
// Execute any logic that should take place if the save fails.
// error is a Parse.Error with an error code and message.
console.log('Failed to create new object, with error code: ' + error.message);
}
});
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 user = task.get("user");
user.fetch({
success: function(user) {
//fetch user is here
}
});
This is explained here: https://parse.com/docs/js_guide#objects-pointers
The problem with your script is when you are querying in Parse it is done asynchronously so you can't return the user immediately. Instead you need to return the promise and then handle it when you call getUserFromUsername:
function getUserFromUsername(username) {
var User = Parse.Object.extend("_User");
var query = new Parse.Query(User);
query.equalTo("username", username);
return query.first();
}
getUserFromUsername('testUsername').then(function(result) {
//use User here
}, function(error) {
alert("Error: " + error.code + " " + error.message);
});
Take a look at this document on promise chaining for more information about promises:

Parse Background Job Not Saving Objects

Okay I'm trying to set these objects in the user class, but for some reason it's not saving. It's very straight forward, or it seems like it should be:
This gets user:
var actionCompleted = results[i].get("ActionComplete");
var user = results[i].get("User");
This Gets Objects:
var moneyLost = user.get("MoneyLost");
var daysRow = user.get("DaysInRow");
var daysWoken = user.get("DaysWoken");
var daysLate = user.get("DaysLate");
This Sets and Saves The Objects:
user.set = ("MoneyLost", moneyLost + bountyVal);
user.set = ("DaysInRow", daysRow++);
user.set = ("DaysWoken", daysWoken++);
user.save(user, {
success: function(gameScore) {
// Execute any logic that should take place after the object is saved.
alert('New object created with objectId: ' + gameScore.id);
},
error: function(gameScore, error) {
// Execute any logic that should take place if the save fails.
// error is a Parse.Error with an error code and message.
alert('Failed to create new object, with error code: ' + error.message);
}
});
And This Sets and Saves More Objects:
user.set = ("DaysInRow",0);
user.set = ("DaysLate", daysLate++);
user.save(user, {
success: function(gameScore) {
// Execute any logic that should take place after the object is saved.
alert('New object created with objectId: ' + gameScore.id);
},
error: function(gameScore, error) {
// Execute any logic that should take place if the save fails.
// error is a Parse.Error with an error code and message.
alert('Failed to create new object, with error code: ' + error.message);
}
});
Your syntax is off and you need to do pre-increment rather than post.
var actionCompleted = results[i].get("ActionComplete");
var user = results[i].get("User");
var moneyLost = user.get("MoneyLost");
var daysRow = user.get("DaysInRow");
var daysWoken = user.get("DaysWoken");
var daysLate = user.get("DaysLate");
user.set("MoneyLost", moneyLost + bountyVal);
user.set("DaysInRow", ++daysRow);
user.set("DaysWoken", ++daysWoken);
user.save(null, {
success: function(gameScore) {
// Execute any logic that should take place after the object is saved.
alert('New object created with objectId: ' + gameScore.id);
},
error: function(gameScore, error) {
// Execute any logic that should take place if the save fails.
// error is a Parse.Error with an error code and message.
alert('Failed to create new object, with error code: ' + error.message);
}
});
user.set("DaysInRow", 0);
user.set("DaysLate", ++daysLate);
user.save(null, {
success: function(gameScore) {
// Execute any logic that should take place after the object is saved.
alert('New object created with objectId: ' + gameScore.id);
},
error: function(gameScore, error) {
// Execute any logic that should take place if the save fails.
// error is a Parse.Error with an error code and message.
alert('Failed to create new object, with error code: ' + error.message);
}
});

Parse Cloud Code Queries Return Nothing

I'm attempting to use Cloud Code on Parse to delete pre-existing rows as new rows are added.
This is the current code I've put together:
var queryGoals = new Parse.Query(Parse.Object.extend('Goal'));
queryGoals.include('user');
queryGoals.equalTo('user', request.user);
queryGoals.find({
success: function(results) {
console.warn('Query Returned: ' + results.length);
Parse.Object.destroyAll(results);
},
error: function(user, error) {
console.warn('Error ' + error.code + ': ' + error.message);
}
});
The console never shows the number of records returned (I assume because none are), nor any errors. The same code (with Parse.User.current() for the user filter, of course) returns the expected number of rows when run client-side.
Do queries operate differently when executed by Cloud Code, or have I overlooked something?
I filed a bug report with Parse and finally ended up finding out that the function was ending before the success function was executed since it was running asynchronously. I added in the proper promise structure to get it working as expected (Additional Details):
queryGoals.find(
{
useMasterKey: true,
success: function(results)
{
Parse.Object.destroyAll(results);
},
error: function(user, error)
{
console.warn('Error ' + error.code + ': ' + error.message);
}
}).then(
function(object)
{
// Do Post-Query Stuff Here
response.success();
},
function(error)
{
console.warn('Error ' + error.code + ': ' + error.message);
}
);

Parse - Check for Update inside BeforeSave in Cloud Code

I want to check that I am not saving a duplicate entry for the attend status of an event - so on BeforeSave I am checking that the event rsvp has not already been entered - if it has, I want to know if it needs to be updated. If it does, I want to do an update instead of create a new RSVP entry.
This is my code - I can't seem to get it to work, even with the simplist update inside BeforeSave.
Parse.Cloud.beforeSave("Rsvps", function(request, response) {
var eventid = request.object.get("eventid");
var userid = request.object.get("userid");
var rsvp_status = request.object.get("rsvp_status");
var Rsvps = Parse.Object.extend("Rsvps");
var query = new Parse.Query(Rsvps);
query.equalTo("eventid", eventid);
query.equalTo("userid", userid);
query.first({
success: function(object) {
if (object) {
// response.error("An RSVP for this event already exists.");
request.object.id = object.id;
request.object.set('rsvp_status', "attending");
request.object.save();
} else {
response.success();
}
},
error: function(error) {
response.error("Error: " + error.code + " " + error.message);
}
});
});
I've tried so many variation of this without any joy - this my latest attempt.
#CityLogic you shouldn't have to call that second save in #ahoffer's example, because you are in the beforeSave trigger. Just set the resp_status and call response.success().
UPDATED. I added a check not to not update an existing object if the 'attending' value is correct. Give this a try. If there are any you cannot resolve, add the errors as a comment to this answer.
Parse.Cloud.beforeSave("Rsvps", function (request, response) {
var eventid = request.object.get("eventid");
var userid = request.object.get("userid");
var rsvp_status = request.object.get("rsvp_status");
//Do not re-declare the class
//var Rsvps = Parse.Object.extend("Rsvps");
var query = new Parse.Query("Rsvps");
//Check for existing RSVP
query.equalTo("eventid", eventid);
query.equalTo("userid", userid);
query.first().then(function (object) {
if (object && object.get('rsvp_status') != "attending") {
//RSVP exists and needs updating.
// Do not save the object attached to the request.
//Instead, update existing object.
object.set('rsvp_status', "attending");
object.save().then(function () {
response.error('Updated existing RSVP to "attending"');
},
function (error) {
response.error("Error: " + error.code + " " + error.message);
});
} else {
//Continuing and save the new RSVP object because it is not a duplicate.
response.success();
}
},
function (error) {
response.error("Error: " + error.code + " " + error.message);
});
});

Categories