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");
Related
I am trying to update other user's information in Parse which is stored in User class.
Initially I tried following code:
1.
var user = Parse.User;
var query = new Parse.Query(user);
query.equalTo("name", userName); //to find specific user
query.first({
success: function(results) {
//update that user's details
results.set("name", newName);
results.save();
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
I got following error:
{code: 206, error: "Parse::UserCannotBeAlteredWithoutSessionError"}
2. Then I used Parse.Cloud.useMasterKey(), as I figured out that we can not edit other user's details. But it didn't work either. And master key overrides all security, so it was not a good idea to use this code.
3. So I tried following code:
var user = Parse.User;
var query = new Parse.Query(user);
query.equalTo("objectId", userName);
query.first({
success: function(results) {
results.set("name", newName);
results.save(null, { useMasterKey:true}).then(function(user) {console.log("updated!!!");}, function(error) {console.log(error); });
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
But I am getting '401 Unauthorized' error.
Does anyone know how to update other user's information in Parse? Any help would be greatly appreciated.
You should call fetch function after updated current user object. You can follow below sample:
var currentUser = Parse.User.current();
currentUser.set('name', 'New Name');
currentUser.save(null, {
success: function(user) {
currentUser.fetch();
},
error: function(user, error) {
alert('Failed to update object, with error code: ' + error.message);
}
});
As the question title describes, I've created a custom PFObject class called "User". This class works as expected with the iOS SDK, but when I try and access this class from the Javascript SDK, the query returns null.
Here is the code I use to make the query:
function getUserWithID() {
Parse.initialize("...", "...");
var userID = "someid";
var User = Parse.Object.extend("User");
var query = new Parse.Query(User);
query.equalTo("userID", userID);
query.find({
success: function(results) {
alert("Successfully retrieved " + results.length + " users.");
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
}
Has anyone else run into this issue? Am I missing something or is there an issue with the SDK?
*This same snippet successfully retrieves objects of other classes.
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 im doing a simple query for an object and I am just wondering why when I call the .find() method on query object it returns success even though its an empty array? Here is a sample of my code.
var HuntObject = Parse.Object.extend("HuntObject",{
defaults: {
title: "hunt",
startDate: "",
endDate: "",
prize: "",
players: [],
items: []
}
});
var huntinfo = new Parse.Query(HuntObject);
var user = Parse.User.current().get("username");
huntinfo.notEqualTo("players" , user);
huntinfo.equalTo("title", huntItem);
huntinfo.find({
success: function(results) {
console.log("results")
Console log would give me results = []
I suppose I could just check if results is an empty array and then go from there but I thought that is what using .find was for. Any help would be appreciated.
parse.com would not throw error even if an empty set is retrieved.
A find query will always go in success method if it has been executed properly even if no results are retrieved.
You can check the error using the error code.
var GameScore = Parse.Object.extend("GameScore");
var query = new Parse.Query(GameScore);
query.equalTo("playerName", "Dan Stemkoski");
query.find({
success: function(results) {
alert("Successfully retrieved " + results.length + " scores.");
// Do something with the returned Parse.Object values
for (var i = 0; i < results.length; i++) {
var object = results[i];
alert(object.id + ' - ' + object.get('playerName'));
}
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}});
So if you get an empty array perform required operations in success method only.
try
var HuntObject = Parse.Object.extend("_HuntObject...
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);
});
});