Cant query object by object id - javascript

In my cloud code, I'm trying to query an object from Parse.com right after after I save by using the object id. For some reason its not working right and all the other variations of the starred out line I've tried wont work either. What am I doing wrong?
Parse.Cloud.afterSave("NewMessage", function(leanBody, leanSenderName, leanSenderId, request) {
var query = new Parse.Query("NewMessage");
query.get(request.object.id, { *************************************************
success: function(results) {
console.log("The first object was retrieved");
leanBody = (results.get("MessageBody"));
leanSenderName = (results.get("senderName"));
leanSenderId = (results.get("senderId"));
getUsers(leanBody, leanSenderName, leanSenderId);
results.destroy({
success: function(results) {
console.log("deleted");
}, error: function(results, error){
}
});
}, error: function(error){
}
});
});

Do you have ACL set up for the messages? You may need to use the masterKey.
Parse.Cloud.useMasterKey();

Related

Parse server query each with useMasterKey parameter

I'm migrating from Parse to Parse server. Most of my code is made without promises.
For this to work, I have to send the parameter: useMasterKey: true (where necessary) for each query / save.
For find and get queries or fetch objects, I have no problems, example:
Parse.com (find)
query.find({
success: function(results) {
//...
Parse Server (find)
query.find({useMasterKey: true
}).then(function(results) {
//....
Parse.com (fetch)
user.fetch({
success: function(user) {
//...
Parse Server (fetch)
user.fetch({useMasterKey: true,
success: function(user) {
//....
The problem is with each functions:
Parse.com (each)
query.each(function(comment) {
//...
Parse Server (each)
query.each({useMasterKey: true
}).then(function(comment) {
//....
It does not work.
Thanks
Although the docs don't suggest that the useMasterKey option is supported for an each query, having tested and verified myself it is in fact possible. Syntax as follows:
query.each(callback, {useMasterKey: true})
Where callback is a function that is called for each result of the query.
The each method of a query support useMasterKey, it's passed as an argument after the callback function, that will be executed for each result of the query.
The syntax is:
query.each(function (object, error) {
// Your function code
}, {
useMasterkey: true
})
Where object is a result for the query and error is a possible error that happened.
But, as shown here, it's better to just use useMasterKey for when you're actually changing something in the database:
query.each(function (object, error) {
object.destroy({
success: function (object) {
console.log("Successfully destroyed object.")
},
error: function (error) {
console.log("Error: " + error.code + " - " + error.message)
},
useMasterKey: true
})
})

Parse Server Cloud Code Save Object

I am attempting to query an object add 1 to the returned integer and then save this object back to my mLabs database using parse server cloud code.
I can successfully query and add 1 to the object that I would like, however I cannot figure out how to successfully save this back to the database. I have tried many solutions all leading to a Parse Server "request timeout"
Parse.Cloud.define("addRating", function(request, response) {
var currentRatingQuery = new Parse.Query("StudentNotes");
currentRatingQuery.equalTo("objectId", "Y4bBzvsHb1");
currentRatingQuery.select("noteRating");
currentRatingQuery.find({
useMasterKey: true,
success: function(results) {
//var noteRating = results.get("noteRating");
//noteRating += 1;
results = Number(results);
results += 1;
console.log("NOTE RATINGGGGG: " + results);
console.log("TYPE OFFFFFFF: " + typeof results);
results.set('institution', "TEST INSTITUTION");
results.save(null, {
useMasterKey: true
});
console.log("SAVE SUCCESS", results);
response.success("rating updated successfully.", results);
},
error: function(error) {
response.error("failed to add 1 to parse cloud code rating. Error: " + error); //THIS GETS CALLED
}
});
});
The code above successfully queries the database, but does not save the value back. It results in a Parse Server "request timeout".
My problem was syntax related there is a severe lack of syntax for parse server cloud code due to it being so similar to parse.com cloud code. The following is the working code to retrieve an object and save the object back.
Parse.Cloud.define('addNoteRating', function(request, response) {
var SaveObject = Parse.Object.extend("StudentNotes");
var saveObject = new Parse.Query(SaveObject);
saveObject.equalTo("objectId", request.params.objectId);
saveObject.first({
useMasterKey: true,
success: function(Objects) {
Objects.save(null, {
useMasterKey: true,
success: function(object) {
object.increment("noteRating");
object.save();
console.log("Cloud Code: User note rating has increased by 1.", object);
response.success('Cloud Code: User note rating has increased by 1.');
}
});
}
});
});
Timeout may cause by no response.
Try to add response when api failed, and see what is happened.
BTW, If you what response when increment success, response when save complete.
Parse.Cloud.define('addNoteRating', function(request, response) {
var SaveObject = Parse.Object.extend("StudentNotes");
var saveObject = new Parse.Query(SaveObject);
saveObject.equalTo("objectId", request.params.objectId);
saveObject.first({
useMasterKey: true,
//this function will get at most one object
success: function(object) {
if(object){
object.increment("noteRating");
object.save(null,{
//do not use master key?
success: function(note){
//u should wait the non-blocking call success and finish
console.log("Cloud Code: User note rating has increased by 1.", object);
response.success('Cloud Code: User note rating has increased by 1.');
}, error: response.error
});
}else{
response.error('this student note is not exist');
}
}, error: response.error
});
});
If this object is existed, you can just rewrite your code as below
Parse.Cloud.define('addNoteRating', function(request, response) {
var SaveObject = Parse.Object.extend("StudentNotes");
var studentNote = new SaveObject();
studentNote.id = request.params.objectId;
studentNote.increment("noteRating");
//student.save(null,{useMasterKey:true}).then(
studentNote.save().then(
function(note){
console.log("Cloud Code: User note rating has increased by 1.", object);
response.success('Cloud Code: User note rating has increased by 1.');
}, response.error
)
});

Why can't I wrap js promise resolve in a jquery object?

I wanted to be able to send the data from a successful jquery ajax call to other methods in my application because its quite large and it made coding sense to have one api method to work from, so I opted to try out promises. This is my first shot. I am getting some good results but clearly I am still a bit confused on context and timing.
When I run the following code, I am unable to wrap my return data from the ajax call as a jquery object without getting an error:
var widgetSystem={
listenForClick: function(){
$('div').on('click','a',function(){
var $selectTarget = $(this),
widgetid = $(this).data('widgetid');
apiRequestData = widgetSystem.makeApiRequestForSingleWidget(widgetid);
apiRequestData.then(function(result) {
widgetSystem.showWidget(result);
}).catch(function(e) {
console.log('no way big error ' +e);
});
});
},
makeApiRequest: function(widgetid){
return new Promise(function(resolve, reject) {
$.ajax({
method: "POST",
url: "localhost",
dataType: 'json',
data: {
data: {
widgetId: widgetid
},
action: 'apiMethod'
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
reject();
},
success: function (data) {
resolve(data);
}
});
});
},
showWidget: function(data){
$(data).appendTo('body');
//this causes an exception in my apiRequestData.then function in listenForClick
}
}
I am running un minified jquery and getting the following error in my console:
no way big error TypeError: context is undefined
I don't know exactly what your HTML looks like or how the API is set up, but assuming that the API is working correctly and the data sent via POST is correct, I was able to get it working using jsonplaceholder api with the following code (you can find it on JSbin).
var widgetSystem={
listenForClick: function(){
$('div').on('click','a',function(){
console.log('clicked');
var $selectTarget = $(this);
var widgetid = $(this).data('widgetid');
widgetSystem.makeApiRequest(widgetid)
.then(function(result) {
widgetSystem.showWidget(result);
return result;
})
.catch(function(e) {
console.log('no way big error ' +e);
});
});
},
makeApiRequest: function(widgetid){
return new Promise(function(resolve, reject) {
var root = 'http://jsonplaceholder.typicode.com';
$.ajax({
method: "POST",
url: root+'/posts/',
dataType: 'json',
data: {
userId:1,
title:"Havanagila",
body:"Testing the greatness"
},
success: function(xData, status){
resolve(xData);
//reject('whoops');
},
error: function(xhr, status, error){
reject(status);
}
});
});
},
showWidget: function(data){
$('#space').append(document.createTextNode(JSON.stringify(data)));
}
}
widgetSystem.listenForClick()
I don't think there is an issue which how you are calling resolve(data) within the ajax success callback. There may be an issue with the data being sent to your API such that the error callback is called, which in turn calls reject and causes the callback passed to .catch to be called instead of the intended callback passed to .then.

Accessing json object values in JavaScript

I am trying to build a WebApp which consumes REST API's with Flask.
I am getting my JSON object back successfully from my API but I am unable to display it in the HTML UI.
Consider I am trying to print userid from the JSON file, I am getting the error part only.
Can someone please point me out what is going wrong :
Here is my JSON Object which returns:
Here is my JS file:
$(document).ready(function() {
console.log("ready!");
$('#try-again').hide();
// on form submission ...
$('form').on('submit', function() {
console.log("the form has beeen submitted");
// grab values
valueOne = $('input[name="location"]').val();
console.log(valueOne)
$.ajax({
type: "POST",
url: "/",
data : { 'first': valueOne},
success: function(result) {
if (!$.isEmptyObject({result})) {
$('input').hide();
$('#try-again').show();
$('#result').html(result.userid[0])
$(document).ready(function() {
console.log("ready!");
$('#try-again').hide();
// on form submission ...
$('form').on('submit', function() {
console.log("the form has beeen submitted");
// grab values
valueOne = $('input[name="location"]').val();
console.log(valueOne)
$.ajax({
type: "POST",
url: "/",
data : { 'first': valueOne},
success: function(result) {
if (!$.isEmptyObject({result})) {
$('input').hide();
$('#try-again').show();
$('#result').html(result.userid)
$('#result').html('result.userid')
} else {
$('#result').html('Something went terribly wrong! Please try again.')
}
},
error: function(error) {
console.log(error)
}
});
});
$('#try-again').on('click', function(){
$('input').val('').show();
$('#try-again').hide();
$('#result').html('');
});
});
} else {
$('#result').html('Something went terribly wrong! Please try again.')
}
},
error: function(error) {
console.log(error)
}
});
});
$('#try-again').on('click', function(){
$('input').val('').show();
$('#try-again').hide();
$('#result').html('');
});
});
My JSON DATA:
[{"case": 2005608875,
"filepath": "/x/eng/cs-data/latx/dev/20150510_uploads/wilp/perfstat_20150415_001256/node/10.95.172.19/output.data",
"datatype": "perf8",
"perfdateend": "2015-04-15T02:15:37-04:00",
"userid": "wilp",
"filename": "perfstat_20150415_001256.zip",
"version": "v8.1 ",
"perfdate": "2015-04-15T01:14:24-04:00"}]
There are a couple of issues here, and none of them have anything to do with Flask.
You check the length of the returned JSON object. However, in JS objects do not have a length property, so result.length returns undefined which is not greater than 0.
Since you are using jQuery, you can use its isEmptyObject function to check that your object is not empty.
Also, inside that if statement you are inserting the literal string 'result.userid' into your HTML, instead of the actual userid value of the returned JSON.
if (!$.isEmptyObject(result)) {
...
$('#result').html(result.userid)
}

Parse.com how to get return value of query

in Parse.Com i usually get value of query in the function. How to get it out side of the function?
var TableObject = Parse.Object.extend(TableId);
var qyNewParse = new Parse.Query(TableObject);
qyNewParse.doesNotExist("last_sync");
qyNewParse.find({
success: function(results) {
},
error: function(error){
}
});
var something = results.length
for example if i want to get result.length at outside of function. How to get var something value?
You can't have a function return the result of a query, because the function will always return before the query is completed. Instead of having your function return a value, you should give the function its own callback parameter that will be called when the query completes, like:
function some_cback(callback) {
var TableObject = Parse.Object.extend(TableId);
var qyNewParse = new Parse.Query(TableObject);
qyNewParse.doesNotExist("last_sync");
qyNewParse.find({
success: function(results) {
callback(results); //call the callback
},
error: function(error){
}
});
}
//call the function
var something = some_cback(function(response) {
console.log(response);
});
If you're using angular here's an example code you could use. It's handled properly with promises ($q), so basically your code will "wait" until promise if fulfilled and then move forward
runParseFunction = function(param) {
var deferred = $q.defer();
Parse.Cloud.run('myParseFunction', { param: param }, {
success: function(response) {
deferred.resolve(response);
},
error: function(error) {
deferred.reject(error);
}
});
return deferred.promise;
};
Than to call it outside in any other place you just do:
runParseFunction(param).then(function(response) {
console.log(response);
});

Categories

Resources