Constraint-less Parse query returns blank objects - javascript

I've usually been making queries to a class for a single, directed object using the objectId and it's all been working smoothly. However I am now trying to get all of the objects in a given class.
var values;
var Class = Parse.Object.extend(className);
var query = new Parse.Query(Class);
console.log(objectID);
if (typeof objectID !== "undefined") { //if the user specified objectID
query.get(objectID, {
success: function(retrieveObject) {
for (var i = 0; i < keys.length; i++) {
values[i] = query.get(keys[i]);
}
},
error: function(error) {
console.log("Failed to retrieve " + className + ': ' + error.message);
}
});
} else { //if not return all
query.limit(1000);
query.exists("objectId");
query.find({
success: function(results) {
console.log("the results are " + results);
for (var i = 0; i < results.length; i++) {
for (var j = 0; j < keys.length;j ++)
console.log("key " + j + " is " + keys[j]);
console.log("the result for " + j + " is " + results[i]);
var object = results[i];
values[i][j] = object.get(keys[j]);
console.log("the value for the key in result is " + values[i][j]);
}
},
error: function(error) {
console.log("Failed to retrieve " + className + ': ' + error.message);
}
});
}
For the life of me I cannot figure out why this does not work. "results" comes out as an array of the correct number of values, but each is "[object Object]"
Any ideas?

Related

Filter data obtained through GitHub API

I created this function to obtain GitHub issues:
retrieveEnerpriseIssues: function(repoOrg, repoName, callback) {
let data = null;
// token auth
octokit.authenticate({
type: 'basic',
username: config.githubEnterprise.username,
password: config.githubEnterprise.token
});
async function paginate(method) {
let response = await method({
q: "repo:" + repoOrg + "/" + repoName + " is:issue",
per_page: 100
});
data = response.data.items;
var count = 0;
while (octokit.hasNextPage(response)) {
count++;
console.log(`request n°${count}`);
response = await octokit.getNextPage(response);
data = data.concat(response.data.items);
}
return data;
}
paginate(octokit.search.issues)
.then(data => {
callback(data);
})
.catch(error => {
console.log(error);
});
}
It is called in this function which takes the issues, filters out all of the unwanted keys into json format and puts it in my db.
extractToDb: function() {
let gitIssues = null;
for(var i = 0; i < config.githubEnterprise.orgs.length; i++) {
for(var j = 0; j < config.githubEnterprise.orgs[i].repos.length; j++) {
gitHubService.retrieveEnerpriseIssues(
config.githubEnterprise.orgs[i].owner,
config.githubEnterprise.orgs[i].repos[j].repoName,
function(data, err) {
if(err) {
console.log('err: ', err);
} else {
gitIssues = data;
}
gitIssues = JSON.stringify(gitIssues);
gitIssues = JSON.parse(gitIssues);
let issueFormatForDb = null;
for(var i = 0; i < gitIssues.length; i++) {
issueFormatForDb = gitIssues[i];
const body = '{' +
'"github_id": "' + issueFormatForDb.id + '",' +
'"issue_title": "' + issueFormatForDb.title + '",' +
'"issue_number": "' + issueFormatForDb.number + '",' +
'"issue_url": "' + issueFormatForDb.url + '",' +
'"issue_state": "' + issueFormatForDb.state + '"' +
'}';
console.log('Body: ', body);
getGitHubIssues.postToDb(body);
}
});
}
}
}
I'd like to take this a step further by filtering out any issues where the state is closed. How is this done and should it be handled in my retrieveEnerpriseIssues function or my extractToDb?
Possible solution
I tried this in my extractToDb function:
gitIssues = JSON.parse(gitIssues);
gitIssues = _.where(gitIssues, {state: "open"});
let issueFormatForDb = null;
Is it the best solution or is there a better way?
As #givehug stated:
Better use _.filter, or native filter method like
gitIssues = gitIssues.filter(i => i.state === 'open')
I think .where was deprecated in later versions of lodash github.com/lodash/lodash/wiki/Deprecations. Other than that its perfectly fine.
I just realsied I can filter the state in my paginate function with this:
let response = await method({
q: "repo:" + repoOrg + "/" + repoName + " is:issue" + " label:issue_label" + " state:open",
per_page: 100
});

Javascript - Using promise for post PHP, get undefined result

I'm a newbie in JS and have a little to no knowledge about asynchronous program and promise. I have a problem in getting result from post PHP as written in this code:
showModalLink = function(d, i) {
$('#myModalLabel').text(d.source.name + ' - ' + d.target.name);
$('#modalJum').text(d.jumlahlelangsama);
var lelang = d.daftarlelangsama.split(", ");
var lelangmodal = [];
var promises = [];
for (var i = 0; i < lelang.length; i++) {
querystring = "select pemenang from lelang where id = " + lelang[i];
console.log(querystring);
var queryobj = {
query: querystring
};
promises.push($.post('indikasi3modal.php', queryobj));
}
Promise.all(promises).then(function(results) {
if (results[i] == d.source.name) {
console.log("1");
lelangmodal.push(lelang[i] + " - dimenangkan oleh " + d.source.name);
console.log(lelangmodal);
}
else if (results[i] == d.target.name) {
console.log("2");
lelangmodal.push(lelang[i] + " - dimenangkan oleh " + d.target.name);
console.log(lelangmodal);
}
else {
console.log("3");
lelangmodal.push(lelang[i]);
console.log(lelangmodal);
}
$('#modalLelang').text(lelangmodal);
$('#myModal').modal('show');
});}
I have no idea why the results[i] return undefined inside then function loop. Any help (or alternative ways to solve this) appreciated. Thanks!
I have no idea why the results[i] return undefined inside then function loop.
Because you don't have a loop in the .then() function. So i has the value it had at the end of the loop that created all the promises, which is the number of promises that were created. But the indexes of results go from 0 to i-1.
Promise.all(promises).then(function(results) {
for (var i = 0; i < results.length; i++) {
if (results[i] == d.source.name) {
console.log("1");
lelangmodal.push(lelang[i] + " - dimenangkan oleh " + d.source.name);
console.log(lelangmodal);
} else if (results[i] == d.target.name) {
console.log("2");
lelangmodal.push(lelang[i] + " - dimenangkan oleh " + d.target.name);
console.log(lelangmodal);
} else {
console.log("3");
lelangmodal.push(lelang[i]);
console.log(lelangmodal);
}
}
$('#modalLelang').text(lelangmodal);
$('#myModal').modal('show');
});

For loop jumping to condition

I wonder if anyone can see a problem with this for loop.
I'm using parse, the for loop is inside a success callback for an object query.
When the loop runs, i jumps to response.length before it even finishes it's first loop
var e = [];
for (i = 0; i < response.length; i++) {
console.log("length: " + response.length);
var query = new Parse.Query(conEvent.Events);
query.get(response[i].get("eventID"), {
success: function (result) {
var object = result;
console.log("i: " + i)
e[i] = {
"name": object.get("name"),
"description": object.get("description"),
"dates": conEvent.datesToArray(object.get("dates")),
"ufDates": object.get("dates"),
"creator": object.get("creator"),
"id": object.id,
"invited": conEvent.getInvited(object.id)
}
console.log(e);
},
error: function (error) {
alert("Error: " + error.code + " " + error.message);
}
});
}
at the moment:
console.log("length: " + response.length); outputs "length: 2"
console.log("i: " + i) outputs "i: 2"
A more contextual view of the loop if anyone needs it:
this.getEvents = function () {
//get all the events user is invited to, list them and list the last....3? actions on the event
//display most likely date
//display number of users voted
//go green when date chosen
console.log("getEvents");
var Invite = Parse.Object.extend("Invite");
var query = new Parse.Query(Invite);
query.equalTo("username", Parse.User.current().get("username"));
query.find({
success: function (response) {
var e = [];
for (i = 0; i < response.length; i++) {
console.log("length: " + response.length);
var query = new Parse.Query(conEvent.Events);
query.get(response[i].get("eventID"), {
success: function (result) {
var object = result;
console.log("i: " + i)
e[i] = {
"name": object.get("name"),
"description": object.get("description"),
"dates": conEvent.datesToArray(object.get("dates")),
"ufDates": object.get("dates"),
"creator": object.get("creator"),
"id": object.id,
"invited": conEvent.getInvited(object.id)
}
console.log(e);
},
error: function (error) {
alert("Error: " + error.code + " " + error.message);
}
});
}
conEvent.myEvents = e;
console.log(e);
$scope.$apply();
}
});
}

Getting Uncaught TypeError: Cannot read property 'get' of undefined in spite of the conditionals

I'm trying to retrieve images on Facebook Parse SDK, and I can't because of this error. And I don't know what i'm doing wrong because I use a conditional in order to no not to create a new variable if this is empty or undefined. This is the code (the console log points the error in the line where i'm creating the var ImageFl):
var Encharcamientos1 = Parse.Object.extend("Report");
var query = new Parse.Query(Inundaciones1);
query.equalTo("Tipo_Reporte", "Encharcamientos");
query.find({
success: function(results) {
// Do something with the returned Parse.Object values
for (var i = 0; i < results.length; i++) {
if (!object.get('ImageFile') || object.get('ImageFile') !== '' || typeof object.get('ImageFile') !== 'undefined') {
var imageFl = object.get('ImageFile');
var imageURL = imageFl.url();
$('.imagen')[0].src = imageURL;
}
var object = results[i];
L.marker([object.get('Latitud'),object.get('Longitud') ], {icon: EncharcamientosIcon}).bindPopup(' <p><span class="grande"> ' + object.get('Tipo_Reporte') + ' </span></p><p>Fecha: ' + object.get('Fecha') + ' </p><p>Hora: ' + object.get('Hora') + '<div class="imagen"></div>' + '</p><p>Comentarios:<br /> ' + noundefined(object.get('Comentario')) + '</p>').addTo(Encharcamientos).addTo(todos);
}
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
The object wasn't being set before the if statement. update, added code from comments
var Encharcamientos1 = Parse.Object.extend("Report");
var query = new Parse.Query(Inundaciones1);
query.equalTo("Tipo_Reporte", "Encharcamientos");
query.find({
success: function(results) {
// Do something with the returned Parse.Object values
for (var i = 0; i < results.length; i++) {
var object = results[i]; // <-- THIS NEEDS TO BE BEFORE IF STATEMENT
var imageFl = object.get('ImageFile');
alert(imageFl);
if (imageFl !== '' && typeof imageFl !== 'undefined') {
var imageURL = imageFl.url();
$('.imagen')[0].src = imageURL;
}
L.marker([object.get('Latitud'),object.get('Longitud') ], {icon: EncharcamientosIcon}).bindPopup(' <p><span class="grande"> ' + object.get('Tipo_Reporte') + ' </span></p><p>Fecha: ' + object.get('Fecha') + ' </p><p>Hora: ' + object.get('Hora') + '<div class="imagen"></div>' + '</p><p>Comentarios:<br /> ' + noundefined(object.get('Comentario')) + '</p>').addTo(Encharcamientos).addTo(todos);
}
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});

JavaScript - "variable undefined" in one part of loop, working in a different part

Using the following code, I'm getting this error RewardPurchases.PurchasesArray[i].Student_Name is undefined:
$('button#random').click( function() {
var Num = Math.floor(Math.random() * Total+1);
Num--;
for (var i in RewardPurchases.PurchasesArray) {
/* --------> */
$('#display').text("Ticker number " + Num + " in the LEAP database belongs to...\n\n\n" + RewardPurchases.PurchasesArray[i].Student_Name.toUpperCase() + " (" + TutorGroup + ")").show().delay(300);
if (i == Num) {
var TutorGroup = '';
Frog.API.get('timetable.getClasses',
{
'params': {'student': RewardPurchases.PurchasesArray[i].Student_ID },
'onSuccess': function(data) {
for (var i = 0; i < data.length; i++) {
if (data[i].subject.name == "Tut Period") {
TutorGroup = data[i].name.replace("/Tp", "");
}
}
}
});
$('#display').animate({'font-size': 36}, 1500, function() {
$(this).prepend('<p>!!! WINNER !!!</p>');
});
alert("Ticker number " + Num + " in the LEAP database belongs to...\n\n\n" + RewardPurchases.PurchasesArray[i].Student_Name.toUpperCase() + " (" + TutorGroup + ")");
}
}
} );
However, if I move this line $('#display').text(... as follows, the error disappears:
$('button#random').click( function() {
var Num = Math.floor(Math.random() * Total+1);
Num--;
for (var i in RewardPurchases.PurchasesArray) {
if (i == Num) {
var TutorGroup = '';
/* --------> */
$('#display').text("Ticker number " + Num + " in the LEAP database belongs to...\n\n\n" + RewardPurchases.PurchasesArray[i].Student_Name.toUpperCase() + " (" + TutorGroup + ")").show().delay(300);
Frog.API.get('timetable.getClasses',
{
'params': {'student': RewardPurchases.PurchasesArray[i].Student_ID },
'onSuccess': function(data) {
for (var i = 0; i < data.length; i++) {
if (data[i].subject.name == "Tut Period") {
TutorGroup = data[i].name.replace("/Tp", "");
}
}
}
});
$('#display').animate({'font-size': 36}, 1500, function() {
$(this).prepend('<p>!!! WINNER !!!</p>');
});
alert("Ticker number " + Num + " in the LEAP database belongs to...\n\n\n" + RewardPurchases.PurchasesArray[i].Student_Name.toUpperCase() + " (" + TutorGroup + ")");
}
}
} );
I don't understand why this is the case? i isn't being defined by the if statement?
I'm trying to display each name in an array, before picking a random name and displaying it in a large font with "WINNER!" above it.
Thanks in advance,
Using for .. in isn't the greatest practice in situations like these. It does a deep dredge of ALL object properties, including functions belonging to the prototype.
The reason why only $('#display').text(... causes you issues is that you try to use a property of a property RewardPurchases.PurchasesArray[i]. Elsewhere, you use it by itself, which won't fail, it will just silently return undefined in those cases. (a.k.a., 'params': {'student': RewardPurchases.PurchasesArray[i].Student_ID }.)
Using a test that you wrap all the code inside your for .. in loop, typeof RewardPurchases.PurchasesArray[i] === 'object' && typeof RewardPurchases.PurchasesArray[i] !== null should do the trick, ensuring that each property that you use in your iterations is simply an object, and not a function or some "scalar" value.
NB: You can also use RewardPurchases.PurchasesArray[i].hasOwnProperty('propertyName'), but it isn't supported universally in all browsers, so the above example I gave is safer and works for your purpose.
What is the integrity of your array like?
//RewardPurchases.PurchasesArray
[0] undefined
[1] { Student_Name: undefined }
[2] { Student_Name: 'Bob' }
The above are all valid in an array. [0] and [1] will both give you the error you received.
If PurchasesArray is not an array but an object - then you need to do a check inside your loop.
for (var i in RewardPurchases.PurchasesArray) {
if(!RewardPurchases.PurchasesArray.hasOwnProperty(i)) {
continue;
}
//rest of code...
}

Categories