using variable to change Parse.com query - javascript

I am using the following Parse.com Javascript query and need to switch the type of query based on a variable.
function searchParseExercises (queryParam, ActiveFilters, searchParam) {
var exercise = [];
var TagSearch = Parse.Object.extend("Exercises");
var query = new Parse.Query(TagSearch);
query.containsAll("tags", ActiveFilters);
query.limit(20);
query.find({
success: function(results) {
var exerciseData = {};
for (var i = 0; i < results.length; i++) {
var object = results[i];
var exerciseData = {
exerciseName : object.get('exerciseName'),
exerciseDescription : object.get('exerciseDescription'),
images : object.get('images'),
}
exercise.push(exerciseData);
}
$scope.allExercises = exercise;
},
error: function(error) {
$ionicPopup.alert({
title: "Error: " + error.code + " " + error.message
});
}
});
}
To clarify the requirement I have both a text search and filter search in my template. If there is a text search then it should perform:
query.contains("exerciseName", searchParam);
If there are ActiveFilters then it should perform this:
query.containsAll("tags", ActiveFilters);
However if both variables are present (searchParam and ActiveFilters)
then it should perform a Compound Query.
I have no idea how I can wire all this up cleanly.

What I understood from your question:
if (ActiveFilters && searchParam) {
Parse.Query.or(ActiveFilters, searchParam).find({
success: function(results) {
// results contains a list of players that either have won a lot of games or won only a few games.
},
error: function(error) {
// There was an error.
}
}
else if (ActiveFilters) {
query.containsAll("tags", ActiveFilters);
}
else if (searchParam) {
query.contains("exerciseName", searchParam);
}

Related

Java Script array get undefined

when I print the whole array it's print.but if I try to print element by element it's print as undefined.this is my function. I print the arrays at end of the function.client functions are used to connect ajax API.i tried to get integer id that matching to a specific string from database via ajax functions and push them into the two arrays.
function fetch() {
var arrayForClass = [];//this is a array get undefined at the end
var arrayForMessage = [];//this is a array get undefined at the end
exceptionPattern ="";
receivedData.length = 0;
var queryInfo;
var queryForSearchCount = {
tableName: "LOGANALYZER",
searchParams: {
query: "_eventTimeStamp: [" + from + " TO " + to + "]",
}
};
client.searchCount(queryForSearchCount, function (d) {
if (d["status"] === "success" && d["message"] > 0) {
var totalRecordCount = d["message"];
queryInfo = {
tableName: "LOGANALYZER",
searchParams: {
query: "_eventTimeStamp: [" + from + " TO " + to + "]",
start: 0, //starting index of the matching record set
count: totalRecordCount //page size for pagination
}
};
client.search(queryInfo, function (d) {
var obj = JSON.parse(d["message"]);
if (d["status"] === "success") {
for (var i = 0; i < obj.length; i++) {
if(obj[i].values._level === "ERROR" || obj[i].values._level === "WARN"){
receivedData.push([{
date: new Date(parseInt(obj[i].values._eventTimeStamp)).toUTCString(),
level: obj[i].values._level,
class: obj[i].values._class,
content: obj[i].values._content,
trace: (obj[i].values._trace ? obj[i].values._trace : ""),
timestamp: parseInt(obj[i].values._eventTimeStamp)
}]);
}else{
continue;
}
}
console.log(receivedData);
for (forLoopI = 0; forLoopI < receivedData.length; forLoopI++){
var className = receivedData[forLoopI][0].class;
var strclassname = className.toString();
var messageContent = receivedData[forLoopI][0].content;
queryInfo = {
tableName: "EXCEPTION_CLASS_FOR_ERROR_PATTERNS",
searchParams: {
query: "class_name: "+ strclassname + "",
start: 0, //starting index of the matching record set
count: 1 //page size for pagination
}
};
client.search(queryInfo,function(d){
var obj = JSON.parse(d["message"]);
if (d["status"] === "success") {
var num = obj[0].values.id;
var strnum = num.toString();
arrayForClass.push(strnum);
}else{
$(canvasDiv).html(gadgetUtil.getCustemText("No content to display","error while creating the error pattern" +
" please try again"));
}
},function(error){
console.log(error);
error.message = "Internal server error while data indexing.";
onError(error);
});
queryInfo = {
tableName: "ERROR_MESSAGE_CONTENTS",
searchParams: {
query: "message: \""+ messageContent + "\"",
start: 0, //starting index of the matching record set
count: 1 //page size for pagination
}
};
client.search(queryInfo,function(d){
var obj = JSON.parse(d["message"]);
console.log(obj);
if (d["status"] === "success") {
var num2 = obj[0].values.id;
var strnum2 = num2.toString();
arrayForMessage.push(strnum2);
}else{
$(canvasDiv).html(gadgetUtil.getCustemText("No content to display","error while creating the error pattern" +
" please try again"));
}
},function(error){
console.log(error);
error.message = "Internal server error while data indexing.";
onError(error);
});
}
}
}, function (error) {
console.log(error);
error.message = "Internal server error while data indexing.";
onError(error);
});
}else{
$(canvasDiv).html(gadgetUtil.getCustemText("No content to display","there are no error patterns which include this error" +
" please try another one"));
}
}, function (error) {
console.log(error);
error.message = "Internal server error while data indexing.";
onError(error);
});
console.log("------------------");
for (var j = 0; j < 8; j++) {
console.log(arrayForClass[j]);//prints undefine
}
console.log("------------------");
console.log(arrayForClass[0]); //prints undefine
console.log(arrayForClass);//prints corectly
console.log(arrayForMessage);//printd corectly
}
Your API call is asynchronous, which mean it's continue working to the next line even your call is not finished.
You get undefined because your console.log reference to the not exists yet variable. arrayForClass is empty at that moment, so arrayForClass[0] is not exists.
Next line you get correct result because you console.log to an existing variable, even it's empty at the moment, but your debugger tool is trying to be smart by update it for you in the console when your data came in.
if you really want to see the actual value at that point, you need to somehow make it immutable, for example :
console.log(JSON.parse(JSON.stringify(arrayForClass)));
This is only explain why you get data in the console like that.If you need to use those variable, It's has to be done inside those callback function regarding each calls.

Parse.Query returning fewer objects than the limit

I am trying to return a list of users from my User class. I have 101 users. I get 90 users back.
I know that Parse queries cap the data at 100 objects unless specified, so I should be getting at least 100. Why am I getting fewer than 100? Where are my stray 11?
Here's my code:
function avAuthTime_C(){
var query = new Parse.Query(Parse.User);
query.limit = 1000;
query.count({
success: function(number) {
// There are number instances of MyClass.
console.log("Total Instances: "+number);
},
error: function(error) {
// error is an instance of Parse.Error.
console.log("Parse error");
}
});
I have heard that Parse is being phased out. We're building an app for a long term school project, and while we'll be working on it for a few months, we'll be done (and graduated!) by the time parse closes.
According to the following post, you should be able to use _limit and _skip, and it should function properly.
Example:
query.count({
success: function(count) {
var chunk = 100;
var cycles = Math.ceil(count / chunk);
for (i = 0; i < cycles; i++) {
var _query = new Parse.Query("ClassName");
_query.descending("createdAt");
_query._limit = chunk;
_query._skip = i * chunk;
console.log("getting results " + _query.skip.toString() + " to " + (_query.skip + _query.limit).toString());
_query.find({
success: function(results) {
var template = $("#ClassNameTemplate").html();
var class_name_html = Mustache.to_html(template, {"ClassName": results});
$("#classNameTable").find("tbody").append(class_name_html);
},
error: function(error) {
console.log("error");
console.log(error);
}
});
}
},
error: function(error) {
console.log("error");
console.log(error);
}
});

How to get the column of parse.com class?

I trying to use Cloud Code to get class's data.
And there are my questions.
Q:In this photo,how do I get the score column?
there is my code.
var object = [];
var pushQuery = new Parse.Query('Meeting');
pushQuery.find({
success: function(results) {
success: function(results) {
for (var i = 0; i < results.length; i++) {
object[i] = results[i];
}
},
error: function(error) {
}
});
You can get column from parse one of following ways.
results[i].get("columnName").
or
results[i].ansId //replace ansId with your column name.

Parse.com JS looping through an array when using query.find()

I'm trying to query using each elements on the array as the constraint, but so far its has only given me one result.
Here is the array:
["C44","C43","C45","C117"]
Here what I have:
{var TestObject = Parse.Object.extend("TestObject");
var query = new Parse.Query(TestObject);
query.get("W7yuUsbbav", {
success: function(testObject) {
var subjectArray = testObject.get("subjects");
for (i = 0; i < subjectArray.length ; i++ ){
console.log(subjectArray[i]);
var query = new Parse.Query("Subjects");
query.equalTo("subCode", subjectArray[i]);
query.find({
success: function(results) {
$scope.$apply(function() {
$scope.subjects1 = results.map(function(obj) {
return {subCode: obj.get("subCode"), subName: obj.get("subName"), subDesc: obj.get("subDesc")};
});
});
},
error: function(error) {
}
});
}
},
error: function(object, error) {
// The object was not retrieved successfully.
// error is a Parse.Error with an error code and message.
}
});}
You can use the containedIn property of query.
var sampleId = "W7yuUsbbav";
var query1 = new Parse.Query("TestObject");
query1.get(sampleId).then(function (testObject) {
// Success
var subjectArray = testObject.get("subjects");
var query2 = new Parse.Query("Subjects");
query2.containedIn("subCode", subjectArray);
return query2.find();
}).then(function (subjectObjects) {
// Success
// results is an array of objects
}, function (error) {
// Error
});

Change URLs into files (Parse.com using Javascript CloudCode)

I need to batch change a number of image links (URL's links that exist within a class in) to image files (that Parse.com hosts).
Cloud code is (apparently) how to do it.
I've followed the documentation here but haven't had any success.
What I wanted to do is:
Take URL link from "COLUMN_1"
Make it a file
Upload file to "COLUMN_1" (overwrite existing URL). If this is dangerous- can upload it to a new column ("COLUMN_2").
Repeat for next row
This code did not work (this is my first time with JS):
imgFile.save().then(function () {
object.set("COLUMN_1", imgFile);
return object.save();
}).then(function (CLASSNAME) {
response.success("saved object");
}, function (error) {
response.error("failed to save object");
});
Can anyone recommend how to do this?
OK- this successfully works for anyone else trying.
Parse.Cloud.job("convertFiles", function(request, status) { //Cuts the rundata out of poor runs
function sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds){
break;
}
}
}
// Tell the JS cloud code to keep a log of where it's upto. Manually create one row (in class "debugclass") to get an object Id
Parse.Cloud.useMasterKey();
var Debug = Parse.Object.extend("debugclass");
var queryForDebugObj = new Parse.Query(Debug);
queryForDebugObj.equalTo("objectId", "KbwwDV2S57");
// Query for all users
// var queryForSublist = new Parse.Query(Parse.Object.extend("gentest"));
queryForDebugObj.find({
success: function(results) {
var debugObj = results[0];
var processCallback = function(res) {
var entry = res[0];
var debugObj = results[0];
debugObj.set("LastObject", entry.id);
debugObj.save();
Parse.Cloud.httpRequest({
url: entry.get("smallImage2"),
method: "GET",
success: function(httpImgFile)
{
console.log("httpImgFile: " + String(httpImgFile.buffer));
var imgFile = new Parse.File("picture.jpg", {base64: httpImgFile.buffer.toString('base64')});
imgFile.save().then(function () {
console.log("2");
entry.set("smallImage1", imgFile);
entry.save(null, {
success: function(unused) {
debugObj.increment("itemDone");
sleep(20);
res.shift();
if (res.length === 0) {
process(entry.id);
return;
}
else {
processCallback(res);
}
},
error: function(unused, error) {
response.error("failed to save entry");
}
});
});
},
error: function(httpResponse)
{
console.log("unsuccessful http request");
response.error(responseString);
}
});
};
var process = function(skip) {{
var queryForSublist = new Parse.Query("genpants");
if (skip) {
queryForSublist.greaterThan("objectId", skip);
console.error("last object retrieved:" + skip);
}
queryForSublist.ascending("objectId");
queryForSublist.find().then(function querySuccess(res) {
processCallback(res);
}, function queryFailed(reason) {
status.error("query unsuccessful, length of result " + result.length + ", error:" + error.code + " " + error.message);
});
}};
process(debugObj.get("LastObject"));
},
error: function(error) {
status.error("xxx Uh oh, something went wrong 2:" + error + " " + error.message);
}
});
});

Categories

Resources