0
votes

I've just started working in Parse by using the cloud code guide https://parse.com/docs/cloud_code_guide but stuck in averageStars project. This is my code:

var Review = {
  "movie" : "The Matrix",
  "stars" : 5
};

Parse.Cloud.define("averageStars", function(request, response) {
  var query = new Parse.Query("Review");
  query.equalTo("movie", request.params.movie);
  query.find({
    success: function(results) {
      var sum = 0;
      for (var i = 0; i < results.length; ++i) {
        sum += results[i].get("stars");
      }
      response.success(sum / results.length);
    },
    error: function() {
      response.error("movie lookup failed");
    }
  });
});

However, after I run the code by using command in the guide, it just returned blank {}.

This is my call to cloud code:

Maou-MacBook-Pro:MyCloudCode maou$ parse deploy
Uploading source files
Finished uploading files
New release is named v22 (using Parse JavaScript SDK v1.3.4)
Maou-MacBook-Pro:MyCloudCode maou$ curl -X POST \
>   -H "X-Parse-Application-Id: tnXgGeoY38YjEbAqcakncPFRkUzaBQ29v5tK1ir7" \
>   -H "X-Parse-REST-API-Key: 1YVzcl0aKATUUHZITsPasP11m0VNLrdVWiisE1YB" \
>   -H "Content-Type: application/json" \
>   -d '{"movie":"The Matrix"}' \
>   https://api.parse.com/1/functions/averageStars
{}
1
First of all, you never access the item at index 0 because of your ++i. Is that a typo? I always prefer to use Crockford's advice and use for (var i = 0; i < whatever; i = i + 1). Very obvious what it's doing. - mbm29414
Hi mbm29414, I've gave it a try but it has the same error. - maou
Try putting in some console.log() statements. You might not be getting a results array that you expect. Try this (just before var sum = 0;): console.log("results: " + JSON.stringify(results));. - mbm29414
Have you actually saved that Review object in the Parse database, or does it only exist in code? (because it needs to be saved in the database for the query to work). - rickerbh
Hi mbm29414, it prints nothing. Hi rickerbh, could you guide me how to save the object in Parse database? I'm not sure that I will code it correctly. - maou

1 Answers

0
votes

I would start debugging by returning some test data early. for example:

start the function with:

response.success(request);

to return the request data and see if the data flow works.

If that works then inside the success function, return the results:

response.success(results);

... and so on until you identify what's broken.