2

I need to update a bunch of objects at once, and I can't find an efficient way to do it all at once since the docs suggest calling .getObjectInBackgroundWithID. I don't have ID's to every object, and even if I did I couldn't pass them all in.

Questions: 1) It would make more sense to call this function in Cloud Code than to handle this all on the client side, right? 2) What's the best way of updating many objects with the same value in a for loop in JS (Cloud Code)/Swift?

slider
  • 2,736
  • 4
  • 33
  • 69

1 Answers1

2

I think you're looking for a query with .findObjects (and its variants) then use PFObject's class method .saveAll (and its variants) to save the array of objects.

Here's a sample:

var query = PFQuery(className:"GameScore")
query.whereKey("playerName", equalTo:"Sean Plott")
query.findObjectsInBackgroundWithBlock {
  (objects: [AnyObject]?, error: NSError?) -> Void in

  if error == nil {
    // The find succeeded.
    println("Successfully retrieved \(objects!.count) scores.")
    // Do something with the found objects
    if let objects = objects as? [PFObject] {
      for object in objects {
        println(object.objectId)
        // Do your manipulation
      }

      // Save your changes to ALL objects
      PFObject.saveAllInBackground(objects, block: {
        (succeeded: Bool, error: NSError!) -> Void in

        if (error == nil) {
            println("Successfully saved \(objects!.count) objects.")
        } else {
            // Log details of the failure
            println("Error: \(error!) \(error!.userInfo!)")
      })
    }
  } else {
    // Log details of the failure
    println("Error: \(error!) \(error!.userInfo!)")
  }
}

CloudCode sample:

var GameScore = Parse.Object.extend("GameScore");
var query = new Parse.Query(GameScore);
query.equalTo("playerName", "Dan Stemkoski");
query.find({
  success: function(results) {
    alert("Successfully retrieved " + results.length + " scores.");
    // Do something with the returned Parse.Object values
    for (var i = 0; i < results.length; i++) {
      var object = results[i];
      alert(object.id + ' - ' + object.get('playerName'));
    }
  },
  error: function(error) {
    alert("Error: " + error.code + " " + error.message);
  }
});
Islam
  • 3,654
  • 3
  • 30
  • 40
  • I know about `.findObjectsInBackground` but I can't update and save those objects in a `for-in` loop. That's my question. I need to query a class, and update each returned object I get in the for loop. – slider Jul 13 '15 at 06:05
  • You can fetch all of your data, update them inside the `.findObjectsInBackground` block and then call PFObject's class method `.saveAllInBackground` (see the edited answer please). – Islam Jul 13 '15 at 07:04
  • How would I do that in Cloud Code so I don't have to handle all of that extra bandwidth from the client? – slider Jul 13 '15 at 17:42