Parse cloud code - query user issue in "normal" function - javascript

I cannot get cloud code to query a user when using a "standard" function...
If I define the function (as below), it works fine...
Parse.Cloud.define("findUser1", function(request, response){
Parse.Cloud.useMasterKey();
var query = new Parse.Query(Parse.User);
query.equalTo("objectId", "2FSYI1hoJ8"); // "2FSYI1hoJ8" is the objectId of the User I am looking for
query.first({
success: function(user){
response.success(user);
},
error: function(error) {
console.error(error);
response.error("An error occured while lookup the users objectid");
}
});
});
In this version, the function will be called, but the query within will not...
function findThisUser(theObject){
console.log("findThisUser has fired... " + theObject); //confirms "theObject" has been passed in
Parse.Cloud.useMasterKey();
var query = new Parse.Query(Parse.User);
query.equalTo("objectId", "2FSYI1hoJ8"); // "2FSYI1hoJ8" is the value of "theObject", just hard coded for testing
query.first({
success: function(users){
console.log("the user is... " + users);
// do needed functionality here
},
error: function(error) {
console.error(error);
}
});
};
Cloud code does not allow global variables, and I do not see how to pass in a variable to a "defined" function from another one. This is crucial as an outside function must be called to run the required tasks on the returned user. (This happens elsewhere and has to happen AFTER everything else does. This is the confirmation, and is supposed to be used by other functions as well) All potential information found to date has not helped, and the only experience I have in server side javascript is what I have cobbled together from other cloud code...
Any ideas on what I am missing?

This link may help, i had similar issue yesterday and after moving the code a little, and having the response.success(user); in my function all worked fine.
Parse Cloud Code retrieving a user with objectId
Not your exact issue - but this may help.
Heres is the code i use now:
Parse.Cloud.define("getUserById", function (request, response) {
//Example where an objectId is passed to a cloud function.
var id = request.params.objectId;
Parse.Cloud.useMasterKey();
var query = new Parse.Query(Parse.User);
query.equalTo("ObjectId", id);
query.first(
{
success: function(res) {
response.success(res);
},
error: function(err) {
response.error(err);
}
});
});

Related

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

Parse File.save() odd behaviour

I'm uploading a picture to parse.com using the following two ways. The first one using promises works, but the other doesn't. Am I missing something very basic?
Method 1:
var parseFile = new Parse.File(name, file);
parseFile.save().then(function (){
console.log('Picture has been successfully saved.');
callback(pictype, parseFile);
}, function (error){
console.log('Picture cannot be saved.', error.toString());
});
Method 2:
var parseFile = new Parse.File(name, file);
parseFile.save(null, {
success: function () {
console.log('Picture has been successfully saved.');
callback(pictype, parseFile);
},
error: function (error) {
console.log('Picture cannot be saved.', error.toString());
}
});
It depends on how the save method on Parse.File is implemented. It clearly returns a promise since that code works...it probably does not support the success and error syntax. Your code will not fail on it however it just doesn't work.
Edit: looking at the documentation you need to specify the options object (containing the success and error methods) as first argument. That is where you now specify null.

Cannot create a pointer to an unsaved ParseObject

I am having troubles referring to a "User" object from inside a query. I have the following code:
Parse.Cloud.define("getTabsBadges", function(request, response) {
var UserObject = Parse.Object.extend('User');
var user = new UserObject();
user.id = request.params.userId;
// Count all the locked messages sent to the user
var receivedMessagesQuery = new Parse.Query('Message');
receivedMessagesQuery.equalTo('status', 'L');
receivedMessagesQuery.equalTo('toUser', user); // THIS LINE GENERATES THE ERROR
receivedMessagesQuery.count({
// more code here
});
});
I call the function using CURL but I always get the following error:
{"code":141,"error":"Error: Cannot create a pointer to an unsaved
ParseObject\n at n.value (Parse.js:14:4389)\n at n
(Parse.js:16:1219)\n at r.default (Parse.js:16:2422)\n at e.a.value
(Parse.js:15:1931)\n at main.js:9:25"}
I am using the exactly same code in another project, the only difference is that instead of counting objects I find them and its works correctly. I have also verified that the tables have a column type of Pointer<_User> in both projects. What's causing the problem?
The error message Cannot create a pointer to an unsaved means that you are trying to use an object which does not exist in the Parse DB.
With var user = new UserObject();, you're creating a new user object. You cannot use it in a query until you save it to Parse.
Instead of creating a new User object and setting it's objectId, do a query for the User object. See code below:
Parse.Cloud.define("getTabsBadges", function(request, response) {
var UserObject = Parse.Object.extend('User');
var query = new Parse.Query(UserObject);
query.get(request.params.userId, {
success: function(user) {
// Count all the locked messages sent to the user
var receivedMessagesQuery = new Parse.Query('Message');
receivedMessagesQuery.equalTo('status', 'L');
receivedMessagesQuery.equalTo('toUser', user); // THIS LINE GENERATES THE ERROR
receivedMessagesQuery.count({
// more code here
});
},
error: function(error) {
// error fetching your user object
}
});
});
Your request.params.userId may be undefined or null, which causes this error.
Your query constraints cannot compare the Parse Object that is created without data (createWithoutData()) using undefined or null as its objectId.

Parse Cloudcode query error 141

If I run the Parse JavaScript code below locally, the query works fine. However, when I adapt the code to run as Parse cloudcode, the same query is not executed, and when I test the query content I get an error with code 141.
I have tested both functions at various points. The parameter comp_id and request.params.comp_id are the same.
Parse JavaScript query (run locally, works fine)
function testOne(comp_id) {
Parse.initialize(*****,*****);
var Competition = Parse.Object.extend("Competition");
var query = new Parse.Query(Competition);
console.log(query); // <~ gets a valid query
query.get(comp_id, {
success: function(competition) {
console.log(competition.id);
},
error: function(competition, error) {console.log(error);}
});
}
Parse cloudcode query (query does not execute, error 141)
Parse.Cloud.define("testOneCloud", function(request, response) {
var comp_id = request.params.comp_id;
var Competition = Parse.Object.extend("Competition");
var query = new Parse.Query(Competition);
msg = query; // <~ gets undefined error 141
query.get(comp_id, {
success: function(competition) {
msg = competition.id; // <~query success code does not get executed
},
error: function(competition, error) {console.log(error);}
});
response.success(msg);
});
Any idea why one of these two seemingly identical Parse programs work and the other doesn't?
It seems the undeclared msg variable is causing the problem. How about (eliminating the extra variable and using promises):
Parse.Cloud.define("testOneCloud", function(request, response) {
var Competition = Parse.Object.extend("Competition");
var query = new Parse.Query(Competition);
query.get(request.params.comp_id).then(function(competition) {
response.success(competition.id);
}, function(error) {
response.error(error);
});
});

Parse with Meteor JS

I am using Parse (http://parse.com) inside a Meteor Application (http://meteor.com)
I am trying to query my Parse Database from the server side, and everything is fine until I get to the query.
I get the following error:
[TypeError: Cannot call method 'getItem' of undefined]
This is what my code looks like: [I have even tried query.find()]
var VITxUser = Parse.Object.extend("VITxMaster");
var query = new Parse.Query(VITxUser);
query.equalTo("fbid", "1231212");
//no errors till here
query.first({
success: function(object) {
if (!object){
//insert the user
var GameScore = Parse.Object.extend("VITxMaster");
var gameScore = new GameScore();
gameScore.set("fbid", profile.id);
gameScore.set("registrationNumber", "12DEV0000");
gameScore.set("VITevents", "true");
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 + 'and fbid: ' + profile.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);
}
});
}
else{
console.log("found object");
console.log(object.get("registrationNumber"));
}
}
});
I can't see a reference to getItem in your code. I suspect however that the issue is due to meteor's variable scoping. Basically in Meteor each file is variable scoped. So you if you had two files file1.js and file2.js they would be wrapped around in a function(){..}.
You would need to remove the variable scoping by not using var to define your variables. Particularly the one's you want to be accessible globally (in other files)

Categories

Resources