parse-platformparse-cloud-code

Parse Cloud Code Setting Relation On User Class


I have an issue with not getting some cloud code to run in Parse. Currently, I pass an objectId of another user who I want to set a review for. In client side, I am saving the review, and capturing that object. I pass that as well up to cloud code. Both show up there, but I cannot figure out the right way to set the relation on this user and apply that review that was created. Code snip is below. Any help would be appreciated before I bang my head against a wall.

Parse.Cloud.define("addReview", async (request, response) => {
   let { userObjId, reviewObj } = request.params;

   const query = new Parse.Query(Parse.User);

   //get the user object to post review of
   try{ 
      let object = await query.get(userObjId, {useMasterKey: true});         
      console.log(object);
      console.log("running");
      object.set('Reviews', new Parse.Object(reviewObj));
      object.save(null, { useMasterKey: true })
      return ("saved relation and updated reviews");
   } catch (err){
      throw new Error(err.message)
   }
});

Solution

  • I assume


    First I'd suggest to name your user object user instead of object, to make it clearer what you're dealing with and make your code easier to understand.

    Since you said, the review object is already successfully saved on server side, I'd recommend to transmit only the reviewId in your request.


    To add an object to a relation, you first need to get the relation property of your user object:
    const reviewsRelation = user.relation('Reviews');

    Then to add the object to the relation just call:
    reviewsRelation.add(user);

    In total, your snippet should look like this:

    Parse.Cloud.define("addReview", async (request, response) => {
       let { userObjId, reviewObjId } = request.params;
    
       const userQuery = new Parse.Query(Parse.User);
       const reviewQuery = new Parse.Query(Parse.Review);
    
       //get the user object to post review of
       try{ 
          let user = await userQuery.get(userObjId, {useMasterKey: true});
          let review = await reviewQuery.get(reviewObjId, {useMasterKey: true});         
          console.log(user);
          console.log("running");
          const reviewsRelation = user.relation('Reviews');
          reviewsRelation.add(review);
          user.save(null, { useMasterKey: true })
          return ("saved relation and updated reviews");
       } catch (err){
          throw new Error(err.message)
       }
    });