1

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!

2 Answers 2

1

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);
});
Sign up to request clarification or add additional context in comments.

1 Comment

Works like a dream! Thanks!
1

Your function returns before the find method returns. This is the async nature of js. Use something like the async.parrallel from the async lib. http://npm.im/async

Update 20150929:

Here's some code to show you how I do it, this is from a side project I was working on. The data was stored in MongoDB and was accessed with the Mongoose ODM. I'm using Async waterfall as I need the value of the async function in the next method ... hence the name waterfall in the async lib. :)

 async.waterfall([
    // Get the topics less than or equal to the time now in utc using the moment time lib
    function (done) {
        Topic.find({nextNotificationDate: {$lte: moment().utc()}}, function (err, topics) {
            done(err, topics);
        });
    },
    // Find user associated with each topic
    function (topics, done) {
        // Loop over all the topics and find the user, create a moment, save it, 
        // and then send the email.
        // Creating moment (not the moment lib), save, sending email is done in the 
        // processTopic() method. (not showng)
        async.each(topics, function (topic, eachCallback) {
                processTopic(topic, eachCallback);
            }, function (err, success) {
                done(err, success);
            }
        );
    }
    // Waterfall callback, executed when EVERYTHING is done
], function (err, results) {
    if(err) {
        log.info('Failure!\n' + err)
        finish(1); // fin w/ error
    } else {
        log.info("Success! Done dispatching moments.");
        finish(0); // fin w/ success
    }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.