How to make a copy of a Parse Object in the Cloud? - javascript

I would like to have a copy if an existing Parse Object, and then make some edits and save it as a new Parse Object rather than setting each field manually.
Here is my cloud function :
Parse.Cloud.define("SharePost", function(request, response) {
var ShareUserID=request.params.ShareUserID;
var UserID=request.params.UserID;
var PostID=request.params.PostID;
Parse.Cloud.useMasterKey();
var user = new Parse.User({id:UserID});
var shareuser = new Parse.User({id:ShareUserID});
var query = new Parse.Query("Feed");
query.get(PostID, {
success: function(post) {
var Post = Parse.Object.extend("Feed");
var newpost = new Post()
// here I would like to get the same object and make some edits o, it
post.save( {
success:function () {
response.success("Success");
},
error:function (pointAward, error) {
response.success(error);
}
}
);
},
error: function(error) {
console.error("Got an error " + error.code + " : " + error.message);
}
});
});

There might be a prettier way, but one way that's sure to work without relying on any subtleties would be this:
function pfClone(fromObject, toObject, keys) {
var _ = require('underscore');
_.each(keys, function(key) {
toObject.set(key, fromObject.get(key));
});
}
call it like this:
// after fetching a post called "post"
var Post = Parse.Object.extend("Feed");
var newpost = new Post();
var keys = ["title", "author" /* ...the keys you want to copy unchanged */ ];
pfClone(post, newpost, keys);
// change other properties of newpost here
Even prettier would be a version that introspects on the passed object, and then builds and initializes the clone. The one inelegance for either of these ideas is that (last time I checked) PFObject doesn't let you introspect the keys, so you're stuck passing in an array of keys.

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.

Parse Promises Multiple httpRequest Cloud Code

I'm writing an iOs app with Parse.com and Cloud Code. Actually I want to retrieve objects which contain one picture and other informations from a website and I want to add them to a class named News. When I run my code, every object is saved (in my class, one row = one retrieved object) but unfortunately the only first one has its picture saved.... Any idea ?
I made a lot of searches about promises (series / parallels) and I think the problem comes from here..
Note : don't worry about myLink, myImgLink : I put this to make my code easy to read !
Parse.Cloud.define("rajouteNews", function(request, response) {
Parse.Cloud.httpRequest({ url: 'myUrl'}).then(function(httpResponse) {
var news = [];
var NewsClass = Parse.Object.extend("news");
for (var i = 0; i < 10 ; ++i) {
var maNews = new NewsClass();
maNews.set("link", myLink[i]); // "Other informations"
maNews.set("imgLink", myImgLink[i]);
maNews.set("title", myTitle[i]);
var promises = [];
promises.push(Parse.Cloud.httpRequest({
url: $('img').attr('src'),
method: 'GET',
}).then(function(httpResponse){
var imgFile = new Parse.File("photo.jpg", {base64:httpResponse.buffer.toString('base64')});
maNews.set("image",imgFile); // The picture
return maNews.save();
}));
news.push(maNews);
}
promises.push(Parse.Object.saveAll(news, {
success: function (list) {
response.success(news.length.toString() + " ont été sauvegardées");
},
error: function (list, err) {
response.error("Error adding news");
}
}));
return Parse.Promise.when(promises);
}).then(function(bla,result){
response.success("Job done");
}, function(error) {
response.error(error);
}
);
});
Your promises array should put out of the for loop scope. Otherwise , your promise array would be assigned to be a new blank array each loop.
Parse.File would be saved automaticly when its parent do save, you don't need to save it in advance.
So I improve your code as following, try it and tell me weather it works.
Parse.Cloud.define("rajouteNews", function(request, response) {
Parse.Cloud.httpRequest({
url: 'myUrl'
}).then(function(httpResponse) {
var promises = [];
var NewsClass = Parse.Object.extend("news");
for (var i = 0; i < 10; ++i) {
var maNews = new NewsClass();
maNews.set("link", myLink[i]); // "Other informations"
maNews.set("imgLink", myImgLink[i]);
maNews.set("title", myTitle[i]);
var maNewsPromise = Parse.Cloud.httpRequest({
url: $('img').attr('src'),
method: 'GET',
}).then(function(httpResponse) {
var imgFile = new Parse.File("photo.jpg", {
base64: httpResponse.buffer.toString('base64')
});
maNews.set("image", imgFile); // The picture
return maNews.save();
});
promises.push(maNewsPromise);
}
return Parse.Promise.when(promises)
}).then(function(bla, result) {
// this function is call when `Parse.Promise.when(promises)` is done,
//I can't figure out why you take two params.
response.success("Job done");
}, function(error) {
response.error(error);
});
});

Taking data from a javascript object queried from parse.com

I have a parse.com database which i am querying using the objectID. It returns the data but I can only see it inside the promise object as an attribute, i can't figure out how this works from the documentation, how should i actually get the data and turn it into an object rather than a Promise. Should i call the function after or save it as a variable or something in the success function, do i need to define review somewhere earlier? any example would be awesome
var query = new Parse.Query("business_and_reviews");
var results = new Parse.Object("business_and_reviews");
query.get("pLaARFh2gD", {
success: function(results) {
// results is an array of Parse.Object.
},
error: function(object, error) {
// The object was not retrieved successfully.
// error is a Parse.Error with an error code and message.
}
});
var name = results.get("city");
console.log(name);
This is the Promise in chrome
get() returns only one object with the id.
var query = new Parse.Query("business_and_reviews");
query.get("pLaARFh2gD", {
success: function(result) {
var name = result.get("city");
console.log(name);
}
});
Here is another example from the document.
var GameScore = Parse.Object.extend("GameScore");
var query = new Parse.Query(GameScore);
query.get("xWMyZ4YEGZ", {
success: function(gameScore) {
var score = gameScore.get("score");
var playerName = gameScore.get("playerName");
var cheatMode = gameScore.get("cheatMode");
},
error: function(object, error) {
// The object was not retrieved successfully.
// error is a Parse.Error with an error code and message.
}
});
Thanks, I solved it now, first had to be inside the success: function, then had to select the info in the object as follows:
var query = new Parse.Query("business_and_reviews");
var results = new Parse.Object("business_and_reviews");
query.get("pLaARFh2gD", {
success: function(results) {
console.log(results["attributes"]["city"]);
},
error: function(object, error) {
}
});

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

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