Delete specific object from Parse.com

ian picture ian · Oct 6, 2014 · Viewed 8.6k times · Source

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.

Answer

kingspeech picture kingspeech · Oct 6, 2014

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.