In my cloud code I want to retrieve the first object in the "Messages" class. Then i want to grab some information from that object, send it to another class, and finally delete that object from the "Messages" class i originally pulled it from. Below is my code, however it doesn't work. How should i rework this?
Should i use a different approach than the "destroy" method such as collection.remove?
Parse.Cloud.afterSave("sendMessage", function(Parse.Message, response) {
var body = null;
var senderName = null;
var senderId = null;
var randUsers = [];
var query = new.Parse.Query(Parse.Message);
query.find({
success: function(results){
body.push(results[1].get("messageBody"));
senderName.push(results[1].get("senderName"));
senderId.push(results[1].get("senderId"));
results[1].destroy({
success: function(results[1]){
//the first object in the class "Messages" was deleted
}, error: function(results[1], error){
//the first object was not deleted
}
});
response.success(getUsers);
}, error: funtion(error){
response.error("Error");
}
});
});
to avoid confusion: "getUsers" is an arbitrary function call.
Duplicate question with the entry;
Query entire class vs first object in the class
However, if you want to delete a specific object you need something which uniquely identify the
object. Then, one way is using the Parse object id to delete the object from class.
To delete the object via cloud, you need to use the destroy method of ParseObject. But if you have multiple objects then you can use destroyAll method. One example of ParseObject delete method on javascript API is below;
var yourClass = Parse.Object.extend("YourClass");
var query = new Parse.Query(yourClass);
query.get("yourObjectId", {
success: function(yourObj) {
// The object was retrieved successfully.
yourObj.destroy({});
},
error: function(object, error) {
// The object was not retrieved successfully.
// error is a Parse.Error with an error code and description.
}
});
Hope this helps,
Regards.
Some changes into above :
var missingDataQuery = new Parse.Query(missingDataObj)
missingDataQuery.equalTo('projectId',project);
var getMissingData = missingDataQuery.find({
success: function(yourObj) {
console.log('here')
yourObj[0].destroy({})
},
error: function(object, error) {
}
});
Here we getting object and then destroying it.
func deleteImage(imageId: String) {
let query = PFQuery(className: "ClassName")
query.whereKey("imageId", equalTo: "\(imageId)")
query.findObjectsInBackground {
(objects:[PFObject]?, error: Error?) -> Void in
if error == nil && (objects != nil) {
for object in objects! {
object.deleteInBackground()
print("object deleted")
}
}
}
}
Related
I'm using Parse.com as my backend and after Query how can I fill an array with all the data inside the Parse object? how can I avoid re-mapping? example:
$scope.addContList = contacts.map(function(obj) { // re-map!!!!
return {name: obj.get("name")}; // mapping object using obj.get()
});
I'm mapping my Parse object's properties one by one: name: obj.get("name"), etc. is there a better way?
$scope.addContList = [];
var ActivityContact = Parse.Object.extend("ActivityContact2");
var query = new Parse.Query(ActivityContact);
query.equalTo("activityId", $scope.objId);
query.find({
success: function(contacts) {
console.log("Successfully retrieved " + contacts.length + " contact.");
$scope.$apply(function() {
/*$scope.addContList = contacts.map(function(obj) {
return {name: obj.get("name")}; // mapping object using obj.get()
});*/
for (var i = 0; i < contacts.length; i++) {
$scope.addContList.push(contacts.ALL_PROPERTIES); // contacts.ALL_PROPERTIES does not exist, I'm looking a way to do that and avoid mapping?
}
});
console.log("--->>>"+JSON.stringify($scope.addContList, null, 4));
},
error: function(object, error) {
// The object was not retrieved successfully.
// error is a Parse.Error with an error code and message.
}
});
Should I use Underscore library, is that the only way to go?
I have seen some ppl using PFQuery but I don't know what is that, is PFQuery better for this?
Thanks!
The other answers are correct, but I think it's unnecessary to launch a digest cycle every time you add an item from contacts to $scope.addContList. Something like this should be sufficient:
query.find({
success: function (contacts) {
$scope.apply(function () {
// 1) shallow-copy the list of contacts...
// (this is essentially what you are trying to do now)
$scope.addContList = contacts.slice();
// or 2) just assign the reference directly
$scope.addContList = contacts;
// or 3) transform the Parse.Object instances into
// plain JavaScript objects
$scope.addContList = contacts.map(function (c) {
return c.toJSON();
});
});
},
error: function (object, error) {
// The object was not retrieved successfully.
// error is a Parse.Error with an error code and message.
}
});
Options 1) and 2) will correspond to a template similar to
<div ng-repeat="cont in addContList">{{ cont.get('name') }}</div>
while option 3) can be used like
<div ng-repeat="cont in addContList">{{ cont.name }}</div>
If you change
$scope.addContList = contacts[i];
to:
$scope.addContList.push(contacts[i]);
you should be good to go. Your previous code was re-assigning addContList to be each element in the contacts array, instead of adding the element to it. So at the end of your for loop, $scope.addContList would just be the last contact in your contacts array.
Change:
$scope.addContList = contacts[i];
to
$scope.addContList.push(contacts[i]);
I have a user class with two types of users - customers, and vendors. There is a column (GeoPoint) called vendorLocation in user table which has coordinates of the vendor's shop but is left blank (null) for the customers.
When a customer places an order, a new object is created in the Order Class in which I store the address location as a GeoPoint. I want to find the vendor closest to him. I tried to write a cloud code but kept facing the same error over and over.
Parse.Cloud.define("assignVendor", function(request, response){
var orderObjectId = request.params.orderObjectId;
var query= new Parse.Query("Order")
query.equalTo("objectId", orderObjectId);
query.first({
success: function(order){
//order is the newly created parse order object
//console.log("Order object found"+ order.get("orderNumber"));
var userGeoPoint=new Parse.GeoPoint();
//This is the problematic line
userGeoPoint = order.get("customerLocation");
var Query = new Parse.Query(Parse.User);
Query.exists("vendorLocation");
Query.near("vendorLocation", userGeoPoint);
console.log("Reached here");
Query.find({
success: function(results){
var chemist= results[0];
response.success("found "+vendor.get("profileName"));
order.put("vendorLocation", chemist);
order.save(null, {
success: function(result) {response.success("Saved")},
error: function(error) {console.log("Failed at save")} });
},
error:function(error){console.log("Cant find a suitable vendor")}
});
}, error:function(error){console.log("cant find the ");}
});
});
The error shown in cloud code console.
E2015-10-06T11:23:40.858Z]v13 Ran cloud function assignVendor for user 4otr3l7YwG with:
Input: {"orderObjectId":"OS5siGRXYW"}
Result: TypeError: Cannot call method 'get' of undefined
at e.Query.find.success (main.js:25:53)
at e.<anonymous> (Parse.js:14:27927)
at e.s (Parse.js:14:26859)
at e.n.value (Parse.js:14:26278)
at e.s (Parse.js:14:26987)
at e.n.value (Parse.js:14:26278)
at e.s (Parse.js:14:26987)
at e.n.value (Parse.js:14:26278)
at e.<anonymous> (Parse.js:14:26931)
at e.s (Parse.js:14:26859)
I2015-10-06T11:23:40.924Z]Reached here
The android code
HashMap atMap=new HashMap<>();
atMap.put("orderObjectId", "OS5siGRXYW");
ParseCloud.callFunctionInBackground("assignVendor", atMap, new FunctionCallback<String>() {
#Override
public void done(String value, ParseException e) {
if (e!=null){Log.d("failed ", +e.getCode()+e.getMessage());} else {Log.d("s", value);}
}
});
Error showed in android code is exactly the same as console, so I havnt posted it again. Error number is '141'
Here's some help tracking down the cause of your problem.
make absolutely sure that the order number is being passed correctly
and that the order with the object Id you are passing exists.
you may run into problems when directly assigning nested callbacks
to the first() function. It is better to use then() to string promises together.
it is better to use get() than to use first() when trying to
find a single object, as you should get an object not found error
if get() returns nothing, preventing the cannot call method get
error.
Let's clean up your code and see if it helps:
Parse.Cloud.define("assignVendor", function(request, response){
var fetchedOrder;
var orderObjectId = request.params.orderObjectId;
console.log("orderObjectId = " + orderObjectId);
var orderQuery= new Parse.Query("Order")
orderQuery.get(orderObjectId)
.then(function(order){
fetchedOrder = order;
console.log("Order object found"+ fetchedOrder.get("orderNumber"));
userGeoPoint = fetchedOrder.get("customerLocation");
var userQuery = new Parse.Query(Parse.User);
userQuery.near("vendorLocation", userGeoPoint);
return userQuery.first();
})
.then(function(chemist){
order.put("vendorLocation", chemist);
return order.save();
})
.then(function(){
response.success("Success!");
}, function (error){
console.error(JSON.stringify(error));
response.error(error);
});
});
Notes:
You dont need to define a new Parse.Geopoint before getting
customerLocation. You are just reassigning a variable there.
You dont need to check if the vendorLocation exists before
comparing it to the userGeoPoint. If it doesnt exist, it simply
wont get returned when using near
I would advise using response.success only at the end all your
promise thread
After userQuery.find(), I believe that order does not exist in that
context so I've set it as a function variable.
There is no need to use results[0], simply use first()
I created a new column in a table of 10k records. Now I want to update/fill that column with some value. I am using following javascriptcode.
function updateAll(query, updater) {
return query.each(function(object) {
updater(object);
return object.save();
});
}
Parse.Cloud.define('batchUpdateReports', function(request, response) {
// Use the Master Key if you need to override ACLs
Parse.Cloud.useMasterKey();
var Property = Parse.Object.extend('Property');
var query = new Parse.Query(Property);
// Modify the query if you only want to update certain properties
query.notEqualTo('reportType', 'Routine_Inspection');
updateAll(query, function(property) {
// Update the property object as you need
property.set('reportType', 'Routine_Inspection');
}).then(function() {
response.success();
}).fail(function(e) {
response.error(e);
});
});
Nothing is happening and no error in parse log
Thanks in advance
Parse.com and JavaScript SDK.
I have a class called "FriendRequest" which I want to create a relationship with a child class called "myBadges"
The myBadges class stores multiple uploads by different users and I want to link it back to the FriendRequest class so that when I user uploads something, all of these can be accessed via the FriendRequest class using a field name "Item".
At the moment the code looks like this, which is saving the users upload to the "myBadges" class. But how do I add the relationship?
Do I just add this under the success function?
I have created the relationship column "BADGE" in the data browser already
var relation = user.relation("FriendRequest");
relation.add(BADGE);
EXISTING CODE
Parse.initialize("xxxxxxxxx", "xxxxxxxxxxx");
var MyBadges = Parse.Object.extend("myBadges");
var userbadges = new MyBadges();
var user = Parse.User.current();
$(document).ready(function () {
$("#send").click(function () {
var badgeselected = $('#badgeselect .go').attr("src");
userbadges.set("BadgeName", badgeselected);
userbadges.set("fromUser", user);
userbadges.set("BadgeStatus", "BadgeConnected");
userbadges.save(null, {
success: function (results) {
// The object was saved successfully.
console.log(user);
//location.reload();
},
![enter image description here][1]
![enter image description here][3]
you could try reading the Rest API on 'roles' & 'creating roles'
it explains how to add a relation , ie an array of children objs from a diff class
youre using JS so here is some code that also adds an array of children (type=_User):
success: function(parent) {
_role = parent;
qu.get(userId, {
success: function(child) {
//setters on _role
_role.getChildren().add(user);
_role.save();
response.success(_role.toJSON());
},
error: function(object, error) {
console.log('got role, failed on get user');
}
});
}
I'm trying to convert my basic crud operations into an API that multiple components of my application can use.
I have successfully converted all methods, except the update one because it calls for each property on the object to be declared before the put request can be executed.
controller
$scope.update = function(testimonial, id) {
var data = {
name: testimonial.name,
message: testimonial.message
};
dataService.update(uri, data, $scope.id).then(function(response) {
console.log('Successfully updated!');
},
function(error) {
console.log('Error updating.');
});
}
dataService
dataService.update = function(uri, data, id) {
var rest = Restangular.one(uri, id);
angular.forEach(data, function(value, key) {
// needs to be in the format below
// rest.key = data.key
});
// needs to output something like this, depending on what the data is passed
// rest.name = data.name;
// rest.message = data.message;
return rest.put();
}
I tried to describe the problem in the codes comments, but to reiterate I cannot figure out how to generate something like rest.name = data.name; without specifying the name property because the update function shouldn't need to know the object properties.
Here is what the update method looked like before I started trying to make it usable by any of my components (this works)
Testimonial.update = function(testimonial, id) {
var rest = Restangular.one('testimonials', id);
rest.name = testimonial.name;
rest.message = testimonial.message;
return rest.put();
}
How can I recreate this without any specific properties parameters hard-coded in?
Also, my project has included lo-dash, if that helps, I don't know where to start with this problem. Thanks a ton for any advice!
Try like
angular.extend(rest,testimonial)
https://docs.angularjs.org/api/ng/function/angular.extend