Issue with Cloud Code function preventing data from being saved

After successfully testing this code in Angular and getting the correct responses in console.log, I decided to migrate it to cloud code. Since the function manipulates data in the user table, I had to use the master key and implement it in cloud code. However, when running the code on the cloud, it saves the 'duty' column to the user table without any data, even though there should be data to be saved. Additionally, I suspect that the code may not be running past the first Parse Query because the console.log output is empty in the Parse Logs. Can you point out where I might have gone wrong?

'use strict';
var express = require('express');
var app = express();
app.use(express.bodyParser());
var _ = require('underscore');
var server = require('http').createServer(app);

Parse.Cloud.define("updateMerchant", function(request, response) {
    Parse.Cloud.useMasterKey();
    var user = Parse.Object.extend("User")
    var merchantQuery = new Parse.Query(Parse.User);
    var Offers = Parse.Object.extend("Offer");
    var offerQuery = new Parse.Query(Offers);
    var Matches = Parse.Object.extend("Matched");
    var matchQuery = new Parse.Query(Matches);

    var merchantDuty = [];
    var merchants = request.params.data; //I confirmed the validity of this a key value pair where the value is an array of objects.
    var merchantIds = _.map(merchants, function(n){return n.id});
    console.log(merchantIds)

    offerQuery.containedIn("user", merchants);
    offerQuery.limit(1000); 
    offerQuery.find({//CODE STOPS RUNNING?!?
         success: function (offers) {
              var offerIds = _.map(offers, function (n) {
                             return n.id});

    console.log(offers)//this is telling as it does not appear in the Parse log!

    var offersBeta = _.map(offers, function (n) {
        return _.extend(_.find(n), {id: n.id})});

    matchQuery.containedIn("offer", offers);
    matchQuery.limit(1000);
    matchQuery.find({
          success: function (matches) {
               var merchantArray = _.map(_.flatten(matches), function (n) {return _.find(n)});

                var offers3 = _.map(offersBeta, function (n) {return _.extend(n, {
                    Matched: _.filter(merchantArray, function (a) {return a.offer.id == n.id})
                })})

                var duty = function (TotalBill, id) {
                    var promise = new Parse.Promise();
                    merchantQuery.get(id, {
                        success: function (merchantBill) {
                            merchantBill.set("duty", TotalBill);
                            merchantBill.save().then(function(obj){ console.log(obj); }, function(error){console.log(error)})
                        }
                    })
                }

                merchantDuty.push(duty(_.map(offer9, function(n){return n.TotalBill}), _.map(offer9, function(n){return n.id)}));
            },
            error: function(){console.log(error);}
        });
    }
    
    return Parse.Promise.when(merchantDuty).then(function() {
        response.success("Success");
    },
    function(error) {
        response.error("Something is still wrong");
        console.log(error);
    })
})

It seems that nothing is executed between the offerQuery.find and returning Parse.Promise.

Answer №1

Ensure that you pass pointers in

offerQuery.containedIn("user", merchants);
. For more information, refer to this link.

Give this a try:

var _ = require('underscore');


Parse.Cloud.define("updateMerchant", function(request, response) {
  Parse.Cloud.useMasterKey();

  var merchantDuty = [];
  var merchants = request.params.data;//I confirmed the validity of this a key value pair where the value is an array of objects.

  // var merchantIds = _.map(merchants, function(n) {return n.id;});
  // console.log(merchantIds);

  // Since I don't have the merchants request parameter, I'll fake it with some fake users
  var fakeMerchants = [{"username":"Batman","objectId":"f7zZkPx7kT","createdAt":"2015-04-07T19:41:25.014Z","updatedAt":"2015-04-07T19:41:25.014Z","__type":"Object","className":"_User"},{"username":"Robin","objectId":"wgG4EfaFN1","createdAt":"2015-04-07T19:41:35.024Z","updatedAt":"2015-04-07T19:41:35.024Z","__type":"Object","className":"_User"}];
  // We can get some users like this:
  // var fakeMerchantsQuery = new Parse.Query(Parse.User);
  // fakeMerchantsQuery.find().then(function(users) {
  //   console.log(users);
  // });

  // Since the 'user' column in Offer Class is a pointer, we need to pass merchant pointers.
  // Otherwise we get the error "pointer field user needs a pointer value"
  // See https://www.parse.com/questions/using-containedin-with-array-of-pointers
  var fakeMerchantsPointers = _.map(fakeMerchants, function(merchant) { // TODO change to real merchants
    var pointer = new Parse.User();
    pointer.id = merchant.objectId;
    return pointer;
  });

  console.log(fakeMerchantsPointers);

  var offerQuery = new Parse.Query(Parse.Object.extend("Offer"));
  offerQuery.containedIn("user", fakeMerchantsPointers); // TODO change to real merchants
  offerQuery.limit(1000);
  offerQuery.find().then(function(offers) {

    console.log("inside offer query");
    console.log(offers);

    // Here I assume that the column 'offer' is a Pointer
    var matchQuery = new Parse.Query(Parse.Object.extend("Matched"));
    matchQuery.containedIn("offer", offers);
    matchQuery.limit(1000);
    return matchQuery.find();

  }).then(function(matches){

    console.log("inside matches query");
    console.log(matches);

    // Add the duty stuff here...        

    // We must call success or error
    response.success("Success");

  });

});

Let me know if it worked.

Please keep in mind not to mix Cloud Code with ExpressJS code. The Cloud Code should be in main.js, and the ExpressJS code in app.js. Then, in Cloud Code main.js call require('cloud/app.js'); if you want the request pass through ExpressJS.

Answer №2

The statement

return Parse.Promise.when(merchantDuty)
is being executed prematurely as there are no promises in the merchantDuty array at that point (which was initialized as empty). As a result, the entire function completes before the query finds success.

To resolve this issue, I recommend creating and adding query promises to the merchantDuty array.

Additionally, it would be beneficial to utilize promise callbacks for the query methods. For example:

query.find().then(function(){
  //success
}, function(error){
  //error
});

You can then chain these promises by returning another promise, leading to a more organized code structure.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to change the background color of a MUI theme in ReactJS by using Css

Currently, I am utilizing Material UI to create a theme that is functioning correctly. However, upon adding <CssBaseline/> to the App.js file, it unexpectedly changes the background color to white instead of the intended #1f262a specified in the inde ...

Learn the methods for successfully transferring dynamic values from Angular to a jQuery script

This is the script that I have included in my HTML code: <div class="progress-bar"></div> <script type="text/javascript"> $('.progress-bar').gradientProgressBar({ value: $(this).attr('$scope.moodvalue'), ...

Cross-site request forgery (CSRF) vulnerability spanning multiple applications

I am managing 2 separate applications under the same domain. One is hosted on a PHP 5.6 server with a Laravel 5.2 backend and an Angular2 frontend, while the other is on a PHP 5.3 server with a custom framework and a flat JavaScript frontend. Both applicat ...

What is the best approach to dynamically enable or disable a button depending on the state of multiple checkboxes in React.js?

Incorporated within a page is a component responsible for displaying multiple checkboxes and toggles. Located at the bottom of this component is a button labeled confirm, designed to save modifications and initiate a backend update request. A new functio ...

Content OverFlow: DropDown Menu is not overlapping the content, but rather pushing it downwards

In my webpage, I have a drop-down menu that traditionally pushes the content below it down to make space for its items. However, I want the drop-down to overlap the contents below without affecting their position. I've tried various solutions, such a ...

Having trouble with the functionality of JQuery drop feature?

As I delve into implementing drag and drop functionality with JQuery, I encounter a peculiar issue. I have set up 3 'draggable' divs and corresponding 3 'droppable' divs. The intended behavior is for each draggable element to be accepte ...

I'm struggling to activate the eventListener on several elements with the same className or ID. Unfortunately, only the initial child is being triggered in my current code implementation

Hello fellow developers, I'm facing an issue while working on a project. I have about ten menu items with the same ID, and I want to be able to edit each one when it is clicked. Here's what I tried using JavaScript: const menuElement = d ...

Restangular failing to apply headers during post requests

I have been encountering an issue while trying to set the header for a single post request using Restangular. Despite following the documentation here and seeking help from a similar question, the request is being sent as plain text instead of JSON. My se ...

Click event not functioning correctly in Internet Explorer

When using jQuery, I have the following code: <script type="text/javascript"> $(document).ready(function(){ $('body').on('click', '.add-photo',function() { $("#images").append($('<input/>').attr(&apo ...

Is Angular 1.5 the Best Choice for Structuring Component-Based Applications?

Lately, I've been constructing my application using the following arrangement. /src /components /shared /messagebox /alertbox /Home /About As you can observe, I have shared components that are utilized on ...

Execute Javascript to simultaneously open various links in a single action (not using popups)

I am looking to open multiple URLs with a single click event that also redirects to a specified URL. I have attempted this, but it doesn't seem to be working as intended. Here is the HTML code: <a id="mybutton" href="http://example.net/quote" onc ...

JavaScript struggles to obtain the timezone information when Daylight Saving Time is

Can someone help me with setting a user's timezone offset for PHP through ajax? When a page is loaded with session data, if there is no pre-existing data, the following script is inserted into the page: <script type="text/javascript"> $(doc ...

Converting files to .RAR format using Node.js

Within my current project, I am managing a table of projects. Each project has its own designated column for downloading a PDF file. My goal is to provide users with the capability to download all files and compile them into a single .rar file. Below is th ...

React - assigning a value to an input using JavaScript does not fire the 'onChange' event

In my React application with version 15.4.2, I am facing an issue where updating the value of a text input field using JavaScript does not trigger the associated onChange event listener. Despite the content being correctly updated, the handler is not being ...

How can I identify the main text of a specific <MenuItem/> component in ReactJS Material-UI?

I've been working with the Material-UI Dropdown Menu component and I'm trying to figure out how to console log the primaryText of the selected <MenuItem/>. Can anyone provide guidance on how to achieve this? ...

When JavaScript evaluates special characters in HTML, it interrupts the function call within an AJAX response

Recently, I have been developing a custom form completion feature for a website/tool that I am working on. After successfully implementing the search functionality, which displays results below the input field, I wanted to enable users to select a result ...

The query encoding function of the NextJS router

Encountering an issue while trying to open a new page using NextJS router. The parameter was passed as follows: router.push({ pathname: '/', query: { id: '12344567' }, }) Occasionally, the page redirects to something like: /%3Fid ...

Issue with printing error messages for JavaScript form validation

I have implemented the following code for a form to handle validation and display errors below the fields when they occur: <!DOCTYPE html> <html> <head> <style type="text/css"> .errorcss { background-color: yellow; color:re ...

What is the method for eliminating the box shadow on a table?

Seeking assistance on removing the shadow effect from ng-tables upon hovering. Can someone guide me on how to achieve this? See screenshot here: http://prntscr.com/jcpl5g widget-body { background-color: #fbfbfb; -webkit-box-shadow: 1px 0 10px 1px rgba(0, ...

AngularJS Toggle Directive tutorial: Building a toggle directive in Angular

I'm attempting to achieve a similar effect as demonstrated in this Stack Overflow post, but within the context of AngularJS. The goal is to trigger a 180-degree rotation animation on a button when it's clicked – counterclockwise if active and c ...