How do I work with query results - Javascript (Azure Database) - javascript

so I am using Microsoft Visual Studio 2013 with Apache Cordova at the moment and using Microsoft Azure as the backend database (New to this!). I have written the following code as a test and I can't seem to work with the results of a query. alert(JSON.stringify(results)) seems to work and is alerting the query results as [{"id":"1234","username":"james","password":"james"}]. However, when I try to use results.length or results.'anything', it is not recognising results as an array. Is there a way I can work with the query results? Help is much appreciated :)
function test() {
//Query the Accounts table where the input fields match a record in the table.
var query = accountsTable.where({
username: textUsername.value,
password: textPassword.value
}).read().done(function (results) {
alert(JSON.stringify(results));
var queryTest = results[0].text;
}, function (err) {
alert("Error: " + err);
});
}

You need to specify property name, it seems you are specifying the text, which is not there.
For single record:
var query = accountsTable.where({
username: textUsername.value,
password: textPassword.value
}).read().done(function (results) {
alert(results[0].id + " " + results[0].username + " " + results[0].password);
}, function (err) {
alert("Error: " + err);
});
For multiple records:
var query = accountsTable.where({
username: textUsername.value,
password: textPassword.value
}).read().done(function (results) {
for (var i = 0; i < results.length; i++) {
alert(results[i].id + " " + results[i].username + " " + results[i].password);
}
}, function (err) {
alert("Error: " + err);
});

Related

ParseCloud error 102, cannot query through pointers

I have some problem with parse cloud js.
After I save ParseMessage object, I want to check 3 pointer (product, sender and recipient) in other class (MessageTracker). With the base 3 query there is no problem, but when I call insideQuery.notEqualTo("sender", result.get("owner")); I got an error:
102 : pointer field sender needs a pointer value
This "owner" also a pointer to user class, like the others (sender and recipient), but this time parse cloud send an error.
(On console I see, that the object ids are valid values, so I have the right objects)
Parse.Cloud.afterSave("ParseMessage", function(request) {
var message = request.object;
var product = message.get("product");
var sender = message.get("sender");
var recipient = message.get("recipient");
var query = new Parse.Query("Product");
query.get(product.id, {
success: function(result) {
console.error("prod owner: " + result.get("owner").id + " sender: " + sender.id + " reciever: " + recipient.id);
var insideQuery = new Parse.Query("MessageTracker");
insideQuery.equalTo("product", product);
insideQuery.equalTo("sender", sender);
insideQuery.equalTo("recipient", recipient);
insideQuery.notEqualTo("sender", result.get("owner"));
insideQuery.find({
success: function(results) {
console.error("count: " + results.length);
},
error: function(error) {
console.error("Got an error " + error.code + " : " + error.message);
}
});
},
error: function(object, error) {
}
});
});
Any good advice?
UPDATE
I maybe found the problem. Parse do not let us check equalTo and notEqualTo for the same pointer in the query. Is there any other way to do that?
Try building out the pointer:
var ownerPointer = {
__type: 'Pointer',
className: <className>,
objectId: result.get("owner").id
};
insideQuery.notEqualTo("sender", ownerPointer);

node.js: HTML form hangs after submit when inserting data into PostgreSQL database

I have recently set up node.js using Express and I created a simple HTML form using Jade. The form is to insert the data in a PostgreSQL database. The problem is that when I press submit on the form, everything is inserted on the database, but the HTML form is just hanging/lingering, and at some point it stops with No data received, ERR_EMPTY_RESPONSE. Sometimes it also inserts the data twice. I guess this is because the server side does not return a response, but I cannot see how (I am new to node.js).
The form has action="add_device" which is routed to routes/add_device.js. add_device.js looks like this:
var express = require('express');
var router = express.Router();
router.get('/', function(request, response, next) {
res.send('Nothing to see here. Move along.');
});
router.post('/', function(request, response, next) {
var db = require('../public/javascripts/db/insert');
var result = db.insertDevice(request, response);
return result;
});
module.exports = router;
The insertDevice function in my db module looks like this (it is exported with module.exports):
// Insert new QA device. Data arriving as a request from a HTML form.
insertDevice: function (request, response) {
// Input that is verified in the HTML form.
// Convert to proper format for PostgreSQL query.
var name = '\'' + request.body.name + '\'';
var ip_address = '\'' + request.body.ip_address + '\'';
var os = '\'' + request.body.os + '\'';
// Input that needs to be verified. Prepare for PostgreSQL query.
var mac_address;
var os_version;
request.body.mac_address == "" ? mac_address = 'NULL' : mac_address = '\'' + request.body.mac_address + '\'';
request.body.os_version == "" ? os_version = 'NULL' : os_version = '\'' + request.body.os_version + '\'';
var pg = require('pg'); // PostgreSQL module.
var td = require('./table_data') // Database constants.
var client = new pg.Client(request.app.get('postgreConnection'));
client.connect(function(err) {
if (err) {
return console.error('Could not connect to postgres', err);
}
var QUERY = "INSERT INTO " + td.QA_DEVICES.TABLE_NAME + "(" +
td.QA_DEVICES.COLUMN_NAME + ", " +
td.QA_DEVICES.COLUMN_MAC_ADDRESS + ", " +
td.QA_DEVICES.COLUMN_IP_ADDRESS + ", " +
td.QA_DEVICES.COLUMN_OS + ", " +
td.QA_DEVICES.COLUMN_OS_VERSION + ") VALUES(" +
name + ", " +
mac_address + ", " +
ip_address + ", " +
os + ", " +
os_version + ");";
client.query(QUERY, function (err, result) {
if (err) {
return console.error('Error running query: ' + QUERY, err);
}
console.log('Query performed: ' + QUERY);
client.end();
});
});
}
The 'Query performed' is always logged to console and data inserted into the database, but the form is still hanging. My questions are:
Is it the lack of response from the server that makes the form hang?
How can I "send a response back" to the front end?
Is it possible to route the front end to another page after insertion into the database? What is the best practice?
Yes, your request is receiving no response, so it is hanging.
In order to send a response, you can either send a blind acknowledgement right when the request is received (that is not dependent upon the success of the query and may be bad practice), or you can send it in the callback.
client.query(QUERY, function (err, result) {
if (err) {
// response.json({status: 'error'});
response.write('Error');
return console.error('Error running query: ' + QUERY, err);
} else {
// You can send json here too
// response.json({status: 'success'});
response.write('Success');
}
console.log('Query performed: ' + QUERY);
client.end();
});
If you want to go to another page, simply parse the incoming response on the client side and do a redirect. Using json is a good way to carry this out. You can also do a response.redirect(url) on the server side too, instead of sending back data. Have fun

Parse Javascript SDK Query for PFObject "User" returns nil

As the question title describes, I've created a custom PFObject class called "User". This class works as expected with the iOS SDK, but when I try and access this class from the Javascript SDK, the query returns null.
Here is the code I use to make the query:
function getUserWithID() {
Parse.initialize("...", "...");
var userID = "someid";
var User = Parse.Object.extend("User");
var query = new Parse.Query(User);
query.equalTo("userID", userID);
query.find({
success: function(results) {
alert("Successfully retrieved " + results.length + " users.");
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
}
Has anyone else run into this issue? Am I missing something or is there an issue with the SDK?
*This same snippet successfully retrieves objects of other classes.

Parse.com Query gives success even thought empty set is returned

So im doing a simple query for an object and I am just wondering why when I call the .find() method on query object it returns success even though its an empty array? Here is a sample of my code.
var HuntObject = Parse.Object.extend("HuntObject",{
defaults: {
title: "hunt",
startDate: "",
endDate: "",
prize: "",
players: [],
items: []
}
});
var huntinfo = new Parse.Query(HuntObject);
var user = Parse.User.current().get("username");
huntinfo.notEqualTo("players" , user);
huntinfo.equalTo("title", huntItem);
huntinfo.find({
success: function(results) {
console.log("results")
Console log would give me results = []
I suppose I could just check if results is an empty array and then go from there but I thought that is what using .find was for. Any help would be appreciated.
parse.com would not throw error even if an empty set is retrieved.
A find query will always go in success method if it has been executed properly even if no results are retrieved.
You can check the error using the error code.
var GameScore = Parse.Object.extend("GameScore");
var query = new Parse.Query(GameScore);
query.equalTo("playerName", "Dan Stemkoski");
query.find({
success: function(results) {
alert("Successfully retrieved " + results.length + " scores.");
// Do something with the returned Parse.Object values
for (var i = 0; i < results.length; i++) {
var object = results[i];
alert(object.id + ' - ' + object.get('playerName'));
}
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}});
So if you get an empty array perform required operations in success method only.
try
var HuntObject = Parse.Object.extend("_HuntObject...

Parse - Check for Update inside BeforeSave in Cloud Code

I want to check that I am not saving a duplicate entry for the attend status of an event - so on BeforeSave I am checking that the event rsvp has not already been entered - if it has, I want to know if it needs to be updated. If it does, I want to do an update instead of create a new RSVP entry.
This is my code - I can't seem to get it to work, even with the simplist update inside BeforeSave.
Parse.Cloud.beforeSave("Rsvps", function(request, response) {
var eventid = request.object.get("eventid");
var userid = request.object.get("userid");
var rsvp_status = request.object.get("rsvp_status");
var Rsvps = Parse.Object.extend("Rsvps");
var query = new Parse.Query(Rsvps);
query.equalTo("eventid", eventid);
query.equalTo("userid", userid);
query.first({
success: function(object) {
if (object) {
// response.error("An RSVP for this event already exists.");
request.object.id = object.id;
request.object.set('rsvp_status', "attending");
request.object.save();
} else {
response.success();
}
},
error: function(error) {
response.error("Error: " + error.code + " " + error.message);
}
});
});
I've tried so many variation of this without any joy - this my latest attempt.
#CityLogic you shouldn't have to call that second save in #ahoffer's example, because you are in the beforeSave trigger. Just set the resp_status and call response.success().
UPDATED. I added a check not to not update an existing object if the 'attending' value is correct. Give this a try. If there are any you cannot resolve, add the errors as a comment to this answer.
Parse.Cloud.beforeSave("Rsvps", function (request, response) {
var eventid = request.object.get("eventid");
var userid = request.object.get("userid");
var rsvp_status = request.object.get("rsvp_status");
//Do not re-declare the class
//var Rsvps = Parse.Object.extend("Rsvps");
var query = new Parse.Query("Rsvps");
//Check for existing RSVP
query.equalTo("eventid", eventid);
query.equalTo("userid", userid);
query.first().then(function (object) {
if (object && object.get('rsvp_status') != "attending") {
//RSVP exists and needs updating.
// Do not save the object attached to the request.
//Instead, update existing object.
object.set('rsvp_status', "attending");
object.save().then(function () {
response.error('Updated existing RSVP to "attending"');
},
function (error) {
response.error("Error: " + error.code + " " + error.message);
});
} else {
//Continuing and save the new RSVP object because it is not a duplicate.
response.success();
}
},
function (error) {
response.error("Error: " + error.code + " " + error.message);
});
});

Categories