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

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

Related

Parse : Retrieving properties from an object that is related

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.

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);
});
});

How to retrieve IndexedDB table data to variable?

I have some data in a IndexedDB table that quite simply contains this data:
var Customers = [
{ ssn: "123-45-6666", name: "Andrew", age: 22, email: "andrew#hotmail.com" },
{ ssn: "555-66-7777", name: "Gail", age: 25, email: "gail#email.me" }
];
I then have this function to get data back from the IndexedDB:
function RetrieveTableRows(Table) {
var returnData = [];
var db = window.indexedDB.db;
var trans = db.transaction([Table], "readwrite");
var store = trans.objectStore(Table);
var keyRange = IDBKeyRange.lowerBound(0);
var cursorRequest = store.openCursor(keyRange);
cursorRequest.onerror = window.indexedDB.onerror;
cursorRequest.onsuccess = function(e) {
var result = e.target.result;
if(!!result == false) {
return;
}
returnData.push(result.value);
result.continue();
};
return returnData;
}
I realise that it does not work because the onsuccess function is asynchronous, however I can't my head around a solution.
Simply, I want to be able to write:
var myCustomers = RetrieveTableRows('customers');
and be able to then use the variable myCustomers - is this possible?
I have tried using JQuery.deferred(); method but that didn't seem to work, and I know that I could possibly do something like this:
transaction.oncomplete = function() {
ReturnTableRows(returnData);
};
}
function ReturnTableRows(data) {
//do something with the array of data
}
but I can't work out how to pass this back to the myCustomers variable.
Using the deferred object you should be able to do something like this
function RetrieveTableRows(Table) {
var returnData = [];
//setup deferred object
var defer = $.Deferred();
var db = window.indexedDB.db;
var trans = db.transaction([Table], "readwrite");
var store = trans.objectStore(Table);
var keyRange = IDBKeyRange.lowerBound(0);
var cursorRequest = store.openCursor(keyRange);
cursorRequest.onerror = window.indexedDB.onerror;
cursorRequest.onsuccess = function(e) {
var result = e.target.result;
if(!!result == false) {
//when done resolve the promise, you could also do more
//checking and reject the data so you can handle
//errors
defer.resolve(returnData);
//Make sure we exit the function once we run out of data!
return
}
returnData.push(result.value);
result.continue();
};
//return the promise
return defer.promise();
}
//########### then to use this ###########
//this is now a promise
var myCustomersPromise = RetrieveTableRows('customers');
var myCustomers;
//action todo when promise is resolved/rejected
$.when(myCustomersPromise ).done(function(data){
//do something with the data/assign it to you var here
myCustomers= data;
}).fail(function(data){
});
although i have not actually used indexedDB before so maybe misunderstanding how the query knows it is finished ( I am asssuming result.continue() called the onSuccess again and the result is false when it has gone through all the data) but this is the setup I use when doing anything asynchronously in my apps
An alternate method I've found that uses less code, is a lot simpler and doesn't require JQuery.
Setup:
// Create the function(s) to grab and store the data
var myCustomers;
var getData = {
customers: function(data) {
myCustomers = data
}
}
Call:
//Send the callback function we want into the retrieve function
trans.oncomplete = function (e) {
RetrieveTableRows('Customers', getData.customers)
};
Function:
function RetrieveTableRows(Table, Callback) {
var returnData = [];
var db = window.indexedDB.db;
var trans = db.transaction([Table], "readwrite");
var store = trans.objectStore(Table);
var keyRange = IDBKeyRange.lowerBound(0);
var cursorRequest = store.openCursor(keyRange);
cursorRequest.onerror = window.indexedDB.onerror;
cursorRequest.onsuccess = function(e) {
var result = e.target.result;
if(!!result == false) {
// Send the information back to our specified function
Callback(returnData);
return
}
returnData.push(result.value);
result.continue();
};
}

Parse object not editing successfully

I'm writing a function that queries Parse for a matchCenterItem object associated with the respective user, and then editing certain properties of that object. When the query is made, the response (results) is returned in this form:
<matchCenterItem: 0x7f84e2c1a4b0, objectId: Je1VxP7dPw, localId: (null)> {
categoryId = 9355;
itemCondition = Used;
itemLocation = US;
maxPrice = 350;
minPrice = 250;
parent = "<PFUser: 0x7f84e2c20c10, objectId: kfEHfG4FUD>";
searchTerm = "iphone 5 unlocked";
}
I then want to update the fields with the params being sent. When the function is run, it prints out 'MatchCenterItem successfully edited!', and yet when I check the dashboard, the item hasn't been updated at all. Am I missing something? Full code is below.
Parse.Cloud.define("editMatchCenter", function(request, response) {
var matchCenterItem = Parse.Object.extend("matchCenterItem");
var query = new Parse.Query(matchCenterItem);
query.contains('searchTerm', request.params.searchTerm);
query.equalTo('parent', Parse.User.current())
query.first().then(function(results) {
results.set('minPrice', request.params.minPrice);
results.set('maxPrice', request.params.maxPrice);
results.set('itemCondition', request.params.itemCondition);
results.set('itemLocation', request.params.itemLocation);
results.save();
});
response.success('MatchCenterItem successfully edited!');
});
Changed the code to this and it works now:
Parse.Cloud.define("editMatchCenter", function(request, response) {
var matchCenterItem = Parse.Object.extend("matchCenterItem");
var query = new Parse.Query(matchCenterItem);
query.contains('searchTerm', request.params.searchTerm);
query.equalTo('parent', Parse.User.current())
query.first({
success: function(results) {
results.set('minPrice', request.params.minPrice);
results.set('maxPrice', request.params.maxPrice);
results.set('itemCondition', request.params.itemCondition);
results.set('itemLocation', request.params.itemLocation);
results.save();
response.success('MatchCenterItem successfully edited!');
},
error: function() {
response.error('MatchCenterItem NAAAAT successfully edited!');
}
});
});

How to get properties from an object

I'm using this code to retrieve a simple JSON object:
function userinfo() {
var user = new Object();
$.getJSON('###', function(data){
user.id = data.user.uID;
user.name = data.user.uname;
});
return user;
}
var user = userinfo();
console.log(user);
When I run console.log on the user object outside of the function, I can see the properties of the object (id, name). But when I try to console.log "user.id" or "user.name", they come up as undefined. I can't work out why this is, or what I can do to retrieve the properties without having to iterate over them.
Any suggestions?
The AJAX call to get the JSON is asynchronous, the callback function(data) isn't called until the AJAX returns, but you are reading user right after the AJAX request is sent, but before the AJAX response is received.
Try this:
function userinfo() {
$.getJSON('###', function(data){
var user = new Object();
user.id = data.user.uID;
user.name = data.user.uname;
// Do your stuff here
console.log(user);
});
}
userinfo();
Answer to comment:
Just have a function like this on the app:
function processUser(user){
console.log(user);
}
Then use it in the AJAX callback,
$.getJSON('###', function(data){
var user = new Object();
user.id = data.user.uID;
user.name = data.user.uname;
// Do your stuff here
processUser(user);
});
#Simon, you can do usual application logic in processUser() now, e.g.:
var usersList = []; // Assume this is a global for your app
function processUser(user){
usersList.push(user);
// now other parts of your app can find this user in the list
}
function userinfo(callback) {
$.getJSON('###', function(data){
callback({
id: data.user.uId,
name: data.user.uname
});
});
}
var user;
userinfo(function(newUser) {
user = newUser;
// do work with user.
});
// execution continues here before callback returns. User will not be set.
user.name // error no property name of undefined.
Here's the fix:
function userinfo() {
var user = new Object();
$.ajax({
async: false, //solution right here
url: '/login/user.html',
success: function (data) {
user.id = data.user.uID;
user.name = data.user.uname;
}
});
return user;
}
var user = userinfo();
console.log(user.id);
Works perfectly.

Categories

Resources