Parse Cloudcode query error 141 - javascript

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

Related

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

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

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) {
}
});

JavaScript missing parametar

I am coding a block type plugin for Moodle and have this JS code that gives me problems. Since I'm not very familiar with JS and JSON I can't deduce what is the problem.
My code uses this function to add custom action to action link which issues ajax call to php file ...
This is the code:
function block_helpdesk_sendemail(e) {
e.preventDefault();
Y.log('Enetered method');
var sess = {'sesskey=':M.cfg.sesskey};
Y.log(sess);
var ioconfig = {
method: 'GET',
data: {'sesskey=':M.cfg.sesskey},
on: {
success: function (o, response) {
//OK
var data;
try {
data = Y.JSON.parse(response.responseText);
Y.log("RAW JSON DATA: " + data);
} catch (e) {
alert("JSON Parse failed!");
Y.log("JSON Parse failed!");
return;
}
if (data.result) {
alert('Result is OK!');
Y.log('Success');
}
},
failure: function (o, response) {
alert('Not OK!');
Y.log('Failure');
}
}
};
Y.io(M.cfg.wwwroot + '/blocks/helpdesk/sendmail.php', ioconfig);
}
The code pauses in debugger at return line:
Y.namespace('JSON').parse = function (obj, reviver, space) {
return _JSON.parse((typeof obj === 'string' ? obj : obj + ''), reviver, space);
};
I've put M.cfg.sesskey and data variables on watch. I can see sesskey data shown, but data variable shows like this:
data: Object
debuginfo: "Error code: missingparam"
error: "A required parameter (sesskey) was missing"
reproductionlink: "http://localhost:8888/moodle/"
stacktrace: "* line 463 of /lib/setuplib.php: moodle_exception thrown
* line 545 of /lib/moodlelib.php: call to print_error()
* line 70 of /lib/sessionlib.php: call to required_param()
* line 7 of /blocks/helpdesk/sendmail.php: call to confirm_sesskey()"
And this is what my logs show:
Enetered method
Object {sesskey=: "J5iSJS7G99"}
RAW JSON DATA: [object Object]
As #Collett89 said, the JSON definition is wrong. His tip might work, but if you need strict JSON data then code the key as string (with quotes):
var sess = {'sesskey': M.cfg.sesskey};
or
var sess = {"sesskey": M.cfg.sesskey};
See definition in Wikipedia
your declaring sesskey in a bizarre way.
try replacing data: {'sesskey=':M.cfg.sesskey},
with data: {sesskey: M.cfg.sesskey},
it might be worth you reading through this
mdn link for javascript objects.
You usually need to JSON.stringify() the objects sent via ajax.
which may be part of the problem.

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