Parse : Retrieving properties from an object that is related - javascript

So I am doing a query to bring back a list of records, these records have a link to the user that created the record. The link is to the object.
My query gets me the object but I cant then access the fields of that object (except of course ID)
query.equalTo("search", search);
query.include("user");
query.find({
success: function(Report) {
for (var i = 0; i < Report.length; i++) {
var test = Report[i].id;
query.get(test, {
success: function(result) {
var reportDescription = result.get("reportDescription");
var reportPicture = result.get("reportPicture");
var reportPosition = result.get("reportPosition");
var reportType = result.get("reportType");
var reportDate = result.get("createdAt").toLocaleString();
var reportSearchId = result.get("search").id;
var user = result.get("user")
console.log(user)
var reportSearchBy = user.username;
},
error: function(result, error) {
alert(error.message);
}
});
};
},
error: function(error) {
alert(error.message);
}
});
What am I doing wrong?

i tried to run similar code to what you did. when i tried to access with dot notation i get undefined but when i tried to get it with .get("fieldName") it works..
here is my code:
var FileTest = Parse.Object.extend("FileTest");
var query = new Parse.Query(FileTest);
query.include("user");
query.find().then(function(results){
var lastItem = results[results.length - 1];
if (lastItem){
var user = lastItem.get("user");
console.log(user.get("username"));
}
},function(error){
});
please notice that i also use Promise for better coding and in order to get the username i did lastItem.get("username")
so please try to replace user.username with user.get("username")
and see if it works.

Related

Parse Cloud code query.withinKilometers

(Edit 1)
I'm trying to work with the cloud code and GeoPoint. With the function "query.withinKilometers" I have a pointer to the Location Class but when I try to call the function I get the error "invalid key name". What is the right way to do this? I could not find anything in the documentation, here is a file of the cloud function.
Error: "code":105,"message":"Invalid key name: [object Object]"
here de documentation: http://parseplatform.org/Parse-SDK-JS/api/v1.11.1/Parse.html
Parse.Cloud.define("getCloseFindings", function(request, response){
var query = new Parse.Query("findings");
var locQuery = query.include("location");
var LocQuery = locQuery.get("geoLocation");
var Loc_Lat = request.params.Latitude;
var Loc_Long = request.params.Longitude;
var UserLocation = new Parse.GeoPoint(Loc_Lat,Loc_Long);
var RadiusLocation = request.params.Radius;
query.equalTo("isDeleted", false);
query.withinKilometers(locQuery, UserLocation, 100);
query.find({
success: function(results){
if(results === undefined){
var response_jsonArr = {
code : 404,
message : "Not Found"
};
response.success(response_jsonArr);
}else{
var jsonArr = [];
for ( var i = 0; i < results.length; ++i ) {
var finding_location = results[i].get("location");
jsonArr.push({
name: results
});
}
response.success(jsonArr);
}
}, error: function(error){
response.error(error);
}
});
You are passing an object to query.withinKilometers as the first parameter when you should be passing a String. Try using the key from your query.include call instead, like this:
query.withinKilometers("location", userLocation, 100);

How can I retrieve a list of objects from a class relation?

I have a class Store that has a relation itemsInStore that contains multiple Item objects on Parse. I'm currently trying to Parse Cloud Code to retrieve all Items in a Store, but don't know what a common practice for this is.
In particular, I couldn't find articles that really answer my question here, e.g. how the query should be.
Parse.Cloud.define("retrieveNearbyLocationsAndItemsWithCurrentLocation", function(request, response) {
var Store = Parse.Object.extend("Store");
var store = new Store();
var query = new Parse.Query(Store);
var userGeoPoint = new Parse.GeoPoint(request.params.lat, request.params.long);
query.near("geopoint", userGeoPoint);
query.limit(1);
query.find({
success: function(httpResponse) {
response.success(httpResponse[0].get("itemsInStore"));
console.log(httpResponse[0].get("itemsInStore"));
},
error: function(httpResponse) {
response.error("Error: retrieveNearbyLocationsAndItemsWithCurrentLocation");
}
});
});
Console log would return {"__type":"Relation","className":"Item"}
In order to dig into this Relation and retrieve all Item objects in it, what should be done next?
The relation answers a query. Run that query to get the related elements.
Parse.Cloud.define("retrieveNearbyLocationsAndItemsWithCurrentLocation", function(request, response) {
var Store = Parse.Object.extend("Store");
var store = new Store();
var query = new Parse.Query(Store);
var userGeoPoint = new Parse.GeoPoint(request.params.lat, request.params.long);
query.near("geopoint", userGeoPoint);
query.limit(1);
query.find().then(function(stores) {
if (stores.length && stores[0].relation("itemsInStore")) {
var itemQuery = stores[0].relation("itemsInStore").query();
return itemQuery.find();
} else {
return [];
}
}).then(function(items) {
response.success(items);
}, function(error) {
response.error(error);
});
});

Parse Cloud Code save() doesn't seem to save a field

I'm trying to run save() on a retrieved _User object, but it doesn't seems to save the field I've modified ("ignoredUsers"), which is an array. Although I can see that the save actually went through, as updatedAt does change.
Here is the code:
var query = new Parse.Query(Parse.User);
query.equalTo("objectId", userid1);
query.first({
success: function(result){
var ignored = result.get("ignoredUsers");
if (!ignored) {
ignored = [];
}
ignored.push(userid2);
result.set("ignoredUsers", ignored);
result.save();
}
});
function appendUser(toUser, userId) {
return toUser.fetch({
success: function(user) {
var ignored = user.get("ignoredUsers");
if (!ignored) {
ignored = [];
}
ignored.push(userId);
user.set("ignoredUsers", ignored);
user.save();
}
});
}
Parse.Cloud.job("ignoredUsers", function(request, status) {
Parse.Cloud.useMasterKey();
var query = new Parse.Query("Conversation");
return query.each(function(conversation) {
var participants = conversation.get("participants");
var userid1 = participants[0].id;
var userid2 = participants[1].id;
var user1 = participants[0];
var user2 = participants[1];
return appendUser(user1, userid2).then(function() {
return appendUser(user2, userid1); });
});
status.success();
});
The problem was that the cloud function returned before waiting for the callbacks to finish

Titanium Studio, JavaScript and SQL Error... Cant figure it out

var url = "http://api.reddit.com/";
var dataArray = [];
var working = function(){
var getData = JSON.parse(this.responseText);
var titles = getData.data.children;
for(var i=0, j=titles.length; i<j; i++)
{
var title = titles[i].data.title;
dataArray.push({
title: title,
favorite: 0
});
}
save(dataArray);
}; //working
var save = function(arg){
console.log(arg);
var db = Ti.Database.open("newData");
db.execute('CREATE TABLE IF NOT EXISTS redditTitles (id INTEGER PRIMARY KEY, name TEXT, favorite INTEGER)');
db.execute('INSERT INTO redditTitles (name, favorite) VALUES (?, ?)', arg.title, arg.favorite);
var rowID = db.lastInsertRowId;
//newRow.id = rowID;
//rows.close();
db.close();
gather();
};
var dataContent = [];
var gather = function(){
var db = Ti.Database.open("newData");
var dbRows = db.execute("SELECT name, favorite FROM redditTitles"); // Returns a Result Set object
while(dbRows.isValidRow()){
dataContent.push({
title: dbRows.fieldByName("name"),
fav: dbRows.fieldByName("favorite")
});
console.log("dataContent: "+ dataContent.title);
dbRows.next();
}
dbRows.close();
db.close();
console.log(dataContent);
userInterAPI();
};
var error = function(){
alert("Please check your network connection and try again.");
};
var client = Ti.Network.createHTTPClient({
onload: working,
onerror: error,
timeout: 5000
});
client.open("GET", url);
client.send();
So Basically me and my instructor have been scratching our heads trying to figure out why the arg will show all of the data but after the data is saved and we go to re console log it out, it will show up as null. Not sure why. Someone please help me!
You are saving just one item (Incorrectly - that's why is undefined). If you want to save everything you have to iterate through whole array.
var save = function(arg) {
console.log(arg);
var db = Ti.Database.open("newData");
db.execute('CREATE TABLE IF NOT EXISTS redditTitles (id INTEGER PRIMARY KEY, name TEXT, favorite INTEGER)');
db.execute("BEGIN"); // Transaction
arg.forEach(function(item) {
db.execute('INSERT INTO redditTitles (name, favorite) VALUES (?, ?)', item.title, item.favorite);
//var rowID = db.lastInsertRowId;
});
db.execute("COMMIT");
db.close();
gather();
};
In the function called gather - if you want to see selected title you should use:
console.log(dbRows.fieldByName("name"))
alternatively (This is what you wanted to use):
console.log(dataContent[dataContent.length - 1].title)
instead of
console.log(dataContent.title); // dataContent is an Array.
*Of course you better avoid using dataContent.length in every iteration. That's just an example.

Uncaught TypeError: Object has no method ... Javascript

I'm having an issue where I get an error that says...
"Uncaught TypeError: Object f771b328ab06 has no method 'addLocation'"
I'm really not sure what's causing this. The 'f771b328ab06' is a user ID in the error. I can add a new user and prevent users from being duplicated, but when I try to add their location to the list, I get this error.
Does anybody see what's going wrong? The error occurs in the else statement of the initialize function as well (if the user ID exists, just append the location and do not create a new user). I have some notes in the code, and I'm pretty sure that this is partly due to how I have modified an example provided by another user.
function User(id) {
this.id = id;
this.locations = [];
this.getId = function() {
return this.id;
};
this.addLocation = function(latitude, longitude) {
this.locations[this.locations.length] = new google.maps.LatLng(latitude, longitude);
alert("User ID:" );
};
this.lastLocation = function() {
return this.locations[this.locations.length - 1];
};
this.removeLastLocation = function() {
return this.locations.pop();
};
}
function Users() {
this.users = {};
//this.generateId = function() { //I have omitted this section since I send
//return Math.random(); //an ID from the Android app. This is part of
//}; //the problem.
this.createUser = function(id) {
this.users[id] = new User(id);
return this.users[id];
};
this.getUser = function(id) {
return this.users[id];
};
this.removeUser = function(id) {
var user = this.getUser(id);
delete this.users[id];
return user;
};
}
var users = new Users();
function initialize() {
alert("Start");
$.ajax({
url: 'api.php',
dataType: 'json',
success: function(data){
var user_id = data[0];
var latitude = data[1];
var longitude = data[2];
if (typeof users.users[user_id] === 'undefined') {
users.createUser(user_id);
users.users[user_id] = "1";
user_id.addLocation(latitude, longitude); // this is where the error occurs
}
else {
user_id.addLocation(latitude, longitude); //here too
alert(latitude);
}
}
})
}
setInterval(initialize, 1000);
Since I get the ID from the phone and do not need to generate it here (only receive it), I commented out the part that creates the random ID. In doing this, I had to add a parameter to the createUser method within Users() so that I can pass the ID as an argument from Initialize(). See the changes to createUser below:
Before, with the generated ID (the part where the number is generated is in the above code block with comments):
this.createUser = function() {
var id = this.generateId();
this.users[id] = new User(id);
return this.users[id];
};
After, with the ID passed as an argument:
this.createUser = function(id) {
this.users[id] = new User(id);
return this.users[id];
};
If anyone has any suggestions I would really appreciate it. Thanks!
Here you're getting user_id by :
var user_id = data[0];
So it's a part of the json answer : maybe a string or another dictionnary, this can't be a user object. You should try to update your code in your success function inside the "if" block by :
user = users.createUser(user_id);
//The following line is a non sense for me you put an int inside
//an internal structure of your class that should contain object
//users.users[user_id] = "1";
user.addLocation(latitude, longitude);

Categories

Resources