Search code examples
javascriptjsonparse-platformparse-cloud-code

Retaining objects after parse query in cloud code


I am working on writing some Parse Cloud Code that pulls JSON from a third party API. I would like to modify it, check and see if it already exists and if not, save it. I am having troubles retaining the object after checking if it exists.

Here is an example of what I am trying to do. When I get to the success block, I need the original car object so that I can save it to the parse db. It is undefined though. I am new to JS and am probably missing something obvious here.

for (var j = 0, leng = cars.length; j < leng; ++j) {
    var car = cars[j];          
    var Car = Parse.Object.extend("Car");
    var query = new Parse.Query(Car);           
    query.equalTo("dodge", car.model);
    query.find({
      success: function(results) {
          if (results.length === 0) {
            //save car... but here car is undefined.
          } 
      },
      error: function(error) {
        console.error("Error: " + error.code + " " + error.message);
      }
    });
 }

If anyone could point me n the right direction, I would really appreciate it. Thanks!


Solution

  • Promises will really simplify your life once you get used to them. Here's an example of an update-or-create pattern using promises...

    function updateOrCreateCar(model, carJSON) {
        var query = new Parse.Query("Car");
        query.equalTo("model", model);
        return query.first().then(function(car) {
            // if not found, create one...
            if (!car) {
                car = new Car();
                car.set("model", model);
            }
            // Here, update car with info from carJSON.  Depending on
            // the match between the json and your parse model, there
            // may be a shortcut using the backbone extension
            car.set("someAttribute", carJSON.someAttribute);
            return (car.isNew())? car.save() : Parse.Promise.as(car);
        });
    }
    
    // call it like this
    var promises = [];
    for (var j = 0, leng = carsJSON.length; j < leng; ++j) {
        var carJSON = carsJSON[j];
        var model = carJSON.model;
        promises.push(updateOrCreateCar(model, carJSON));
    }
    Parse.Promise.when(promises).then(function() {
        // new or updated cars are in arguments
        console.log(JSON.stringify(arguments));
    }, function(error) {
        console.error("Error: " + error.code + " " + error.message);
    });