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);
}
});
Related
I have the following call inside my controller:
.controller('OverviewCtrl', function($http, $rootScope, $scope, tipService, alertService) {
var user = $rootScope.sessionUser;
alertService.getAlert(user).then(function(payload) {
$scope.newAlerts = payload;
console.log('got new alerts: ' + $scope.newAlerts);
$rootScope.unreadAlerts = $scope.newAlerts.length;
});
});
And here is the alertService:
.service('alertService', function($rootScope) {
var getAlert = function(user) {
var newAlerts = [];
//function calling business logic for eligible alerts
//set up database query (using Parse)
query.equalTo("user", user);
return query.find({
success: function(results) {
var oldAlerts = results;
for (var i=0; i<alerts.length; i++) {
var isNew = true;
for (var j=0; j<oldAlerts.length; j++) {
if (alerts[i].get("callout") === oldAlerts[j].attributes.callout) {
isNew = false;
}
}
if (isNew) {
newAlerts.push(alerts[i]);
alertToSave = alerts[i];
alertToSave.save(null, {
success: function(alert) {
console.log('successfully saved alert: ' + alert.get("callout"));
},
error: function(error) {
console.log('Failed to save new object, with error code: ' + error.message);
}
});
}
}
console.log('about to return new alerts: ' + newAlerts);
return newAlerts;
},
error: function(error) {
console.log("Error: " + error.code + " " + error.message);
}
});
};
return {
getAlert: getAlert
};
});
What's weird is that the first time this is run (assume there are actually two new alerts), the console.log says this:
about to return new alerts: [object Object],[object Object]
got new alerts:
But the second time this is run, the console.log says this:
about to return new alerts:
got new alerts: [object Object],[object Object]
What's going on? What am I missing here?
UPDATE
For whatever reason, the service was returning the results of the query, not the newAlerts array. As a workaround, I just moved this code into a function in the controller and kept just the business logic for finding eligible alerts in the service.
I don't see anywhere that the alerts array is defined, Nor is anything added to the alerts array. So each time you compare the results/oldAlerts to the alerts array nothing has changed.
I'm not sure why the controller doesn't see anything till the second round. Try using a debugger to step through your code line by line as this should give you a better idea of what is happening
For whatever reason, the service was returning the results of the query, not the newAlerts array. As a workaround, I just moved this code into a function in the controller and kept just the business logic for finding eligible alerts in the service.
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:
So, I'm defining a cloud function that's supposed to make a call to the foursquare api and generate a list of restaurants (each restaurant is a ParseObject) from the returned JSON. I successfully do this, but I run into problems when trying to save these objects to my database and send them back to my phone by calling response.success(). The large code block below saves the list to my database, but if I try
Parse.Object.saveAll(restaurants)
response.success(restaurants)
I end the function before all of the restaurants are saved. I tried using this line instead
Parse.Object.saveAll(restaurants).then(response.success(restaurants))
, but only half of the restaurants get saved before I get the error "Failed with: Uncaught Tried to save an object with a pointer to a new, unsaved object." I also get this error if I call response.success(restaurants) without attempting to save the list. I read that this is a bug in parse preventing someone from printing or passing unsaved ParseObjects. Any ideas? I also tried using .then on the http request, but I get the same issues or a new error: "com.parse.ParseException: i/o failure: java.net.SocketTimeoutException: Read timed out. "
Parse.Cloud.define("callFourSquare", function(request, response) {
//The Parse GeoPoint with current location for search
var geo = request.params.location;
var geoJson = geo.toJSON();
var url = "https://api.foursquare.com/v2/venues/explore?ll=" + geoJson.latitude + ","
+ geoJson.longitude + "§ion=food&sortByDistance=1&limit=50&venuePhotos=1&categoryId=4d4b7105d754a06374d81259&client_id= C043AJBWKIPBAXOHLPA0T40SG5L0GGMQRWQCCIKTRRVLFPTH"
+ "&client_secret=Y1GZZRHXEW1I3SQL3LTHQFNIZRDCTRG12FVIQI5QGUX0VIZP&v=20140715";
console.log(url);
//Call to FourSquare api, which returns list of restaurants and their details
Parse.Cloud.httpRequest({
method: "GET",
url: url,
success: function (httpResponse) {
var restaurants = [];
var json = httpResponse.data;
var venues = json.response.groups[0].items;
console.log(venues.length)
for(i = 0; i < venues.length; i++) {
venue = venues[i].venue;
var RestaurantObject = Parse.Object.extend("Restaurant");
var rest = new RestaurantObject();
try {
rest.set("geoLocation",
new Parse.GeoPoint({latitude: venue.location.lat,
longitude: venue.location.lng}));
} catch(err) {}
try {
rest.set("address", venue.location.address + " " + venue.location.formattedAddress[1]);
} catch(err) {}
try {
rest.set("phoneNumber", venue.contact.formattedPhone);
} catch(err) {}
try {
rest.set("website", venue.url);
} catch(err) {}
rest.set("name", venue.name);
rest.set("lowerName", venue.name.toLowerCase());
try {
rest.set("priceLevel", venue.price.tier);
} catch(err) {}
try {
rest.set("rating", venue.rating/2);
} catch(err) {}
try {
rest.set("storeId", venue.id);
} catch(err) {}
try {
rest.set("icon", venue.photos.groups[0].items[0].prefix + "original"
+ venue.photos.groups[0].items[0].suffix)
} catch(err) {}
restaurants.push(rest);
}
Parse.Object.saveAll(restaurants);
},
error: function (httpResponse) {
response.error("Request failed with response code:" + httpResponse.status + " Message: "
+ httpResponse.text);
}
});
});
I believe your issue is that you aren't returning the Promise from Parse.Object.saveAll(restaurants) when your httpRequest() is complete. Try returning that saveAll() promise and see if it completes.
I'm using JavaScript and parse.com
The below code is not returning any errors in the console log and is creating a new object in parse.com as expected (Under myBadges). But for some reason "BadgeName" is not being captured and is showing as "undefined".
The "BadgeName" column should be populated from the "badgeselected" variable. But "BadgeName" does not appear to being captured as a variable?
Can anyone help me understand why this is happening?
Here is a screen shot of the parse.com backend.
var badgeselected = $("#go").attr("src");
var MyBadges = Parse.Object.extend("myBadges");
var userbadges = new MyBadges();
$(document).ready(function () {
$("#send").click(function () {
userbadges.set("BadgeName", badgeselected);
console.log("done");
userbadges.save(null, {
success: function (results) {
// The object was saved successfully.
location.reload();
},
error: function (contact, error) {
// The save failed.
// error is a Parse.Error with an error code and description.
alert("Error: " + error.code + " " + error.message);
}
});
});
});
Your first line, var badgeselected = $("#go").attr("src");, must also exist inside the $(document).ready callback.
The entire point of that callback is to ensure that the DOM is ready for you to access it. You've put some of your DOM-accessing code inside the callback, but not all of it.
I would have expected the following parse.com/javascript code block to save the selected "badeselected" variable to the parse class "myBadges" and automatically create a relationship back to the "_USer" class.
There are no errors being returned in the console log, however neither are there any records being added to the "myBadges" class.
I'm not sure what error I've made here?
Parse.initialize("XXXXX", "XXXXX");
var badgeselected = $("#go").attr("src")
var contact = Parse.Object.extend("myBadges");
var contact = Parse.User.current();
$(document).ready(function () {
$("#send").click(function () {
contact.set("BadgeName", badgeselected);
console.log("done");
contact.save(null, {
success: function (results) {
// The object was saved successfully.
location.reload();
},
error: function (contact, error) {
// The save failed.
// error is a Parse.Error with an error code and description.
alert("Error: " + error.code + " " + error.message);
}
});
});
});
You are declaring contact twice. First as an extension called myBadges, and then as current user (discarding the first). Check the current user object in the data browser. You should find the badges there.
UPDATE
Here is an example from the javascript guide:
var GameScore = Parse.Object.extend("GameScore");
var gameScore = new GameScore();
gameScore.set("score", 1337);
gameScore.set("playerName", "Sean Plott");
gameScore.set("cheatMode", false);
gameScore.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 description.
alert('Failed to create new object, with error code: ' + error.description);
}
});
You should be able to use this in your jquery code. See how they first declare GameScore as an extension, and then gameScore as new GameScore();
And THEN they set the values on the object.
More info: https://parse.com/docs/js_guide