slider
slider

Reputation: 2816

Update many objects at once in Parse

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?

Upvotes: 2

Views: 193

Answers (1)

Islam
Islam

Reputation: 3734

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

Upvotes: 2

Related Questions