Having trouble obtaining outcomes from Cloud Code in Parse

After struggling with this issue for quite some time, I have reached a point where I feel the need to seek help. I am working on a cloud code function that is supposed to retrieve a list of categories along with their respective products. Each category contains multiple products, with a one-to-many relationship established using pointers. However, I am encountering difficulties in fetching any products.

Here is the code snippet:

Parse.Cloud.define("GetCategories", function(request, response) {
    var _ = require('underscore.js')
    var MSTCATEGORY_CLASS = "MSTCategory";
    var MSTPRODUCT_CLASS = "MSTProduct";
    var CATEGORY_TAG = "Category";
    var SHOP_TAG = "Shop";
    var VIEWS_TAG = "Views";

    var CAT_LIMIT = 10;
    var PROD_LIMIT = 5;

    var productList = [];
    var CatAndProd = [];

    var MSTCategory = Parse.Object.extend(MSTCATEGORY_CLASS);
    var query = new Parse.Query(MSTCategory);
    query.limit(CAT_LIMIT);

    query.find().then(function(results) {
        var promise = Parse.Promise.as();
        _.each(results, function(result) {
            promise = promise.then(function() {
                var MSTProduct = Parse.Object.extend(MSTPRODUCT_CLASS);
                var ProdQuery = new Parse.Query(MSTProduct);
                ProdQuery.equalTo(CATEGORY_TAG, result);
                ProdQuery.include(CATEGORY_TAG);
                ProdQuery.include(SHOP_TAG);
                ProdQuery.descending(VIEWS_TAG);
                ProdQuery.limit(PROD_LIMIT);

                var category = result;
                ProdQuery.find().then(function(ProdResults){
                    ProdResults.forEach(function(product) {
                        productList.push(product);
                    });

                    var singleItem = {
                        "category" : category,
                        "products" : productList
                    };
                    CatAndProd.push(singleItem);
                    return Parse.Promise.as("Hello!");
                });
            });
        });
        return promise;
    }).then(function(hello) {
        var jsonObject = {
            "categoryAndProducts": CatAndProd
        };
        response.success(jsonObject);
    });
});

In essence, my goal is to fetch categories first and then iterate through each category to fetch its products, adding them to a JSON object. Once all categories have been processed, I intend to create an array containing these JSON objects as elements and send it back as a response. Although this seems like a straightforward task, I suspect that there might be logical errors in my approach. As someone new to Javascript and Parse, your guidance would be greatly appreciated.

Answer №1

Here are a few mistakes that need to be addressed:

  • Within your _.each function, you are repeatedly overwriting the same promise object in each iteration.
  • You can directly return your singleItem when resolving the promise, eliminating the need for an additional array.
  • You are utilizing a global productList array, causing the last category to contain all products combined.

Consider implementing the following adjustments to your code:

query.find().then(function(results) {
    var promises = [];

    results.forEach(function(result) {
        var promise = new Parse.Promise();

        var MSTProduct = Parse.Object.extend(MSTPRODUCT_CLASS);
        var ProdQuery = new Parse.Query(MSTProduct);
        ProdQuery.equalTo(CATEGORY_TAG, result);
        ProdQuery.include(CATEGORY_TAG);
        ProdQuery.include(SHOP_TAG);
        ProdQuery.descending(VIEWS_TAG);
        ProdQuery.limit(PROD_LIMIT);

        var category = result;
        ProdQuery.find().then(function(ProdResults) {
            var singleItem = {
                "category" : category,
                "products" : ProdResults
            };

            // Resolve the promise with singleItem directly 
            promise.resolve(singleItem);
        });

        promises.push(promise);
    });

    return Parse.Promise.when(promises); // Return a promise that resolves when all Promises are resolved
}).then(function(allProducts) {
    var jsonObject = {
        "categoryAndProducts": allProducts
    };
    response.success(jsonObject);
});

Additionally, it's advisable not to mix Array.forEach and _.each methods; use one method consistently throughout your code.

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

What is causing the TypeScript error in the MUI Autocomplete example?

I am attempting to implement a MUI Autocomplete component (v5.11) using the example shown in this link: import * as React from 'react'; import TextField from '@mui/material/TextField'; import Autocomplete from '@mui/material/Autoco ...

Generate a dynamic list using NG-Repeat with changing classes

Is there a way to print each item that matches the index of the first loop as an li element with different classes? For instance, having li elements with classes like cat1_li, cat2_li, cat3_li for each respective loop iteration. I'm struggling with ...

Simply output the integer value

Recently, I've been working on a function that I'm trying to condense into a one-liner code for a challenge on Codewars. You can find the problem here. Here's the code snippet that I currently have: export class G964 { public static dig ...

Extract data from the Ajax database and automatically hide the "Load More" button when all items

Every time I fetch data from my MySQL database, I retrieve 5 items at once. $query = $pdo->prepare("SELECT * FROM names WHERE id < ? ORDER BY id DESC LIMIT 5"); $query->execute([$_POST["id"]]); while($row = $query -> fetch() ...

Utilizing getStaticProps for Performance Optimization in Next.js

I am currently in the process of setting up a blog using Next.js and GraphCMS. I have an ArticleList component that I want to display on multiple pages, such as my homepage and under each article as a recommendation. Since the article list is sourced from ...

Utilizing Material UI Grid spacing in ReactJS

I'm encountering an issue with Material UI grid. Whenever I increase the spacing above 0, the Grid does not fit the screen properly and a bottom slider is visible, allowing me to move the page horizontally slightly. Here is the simplified code snippe ...

Validation of nested phone numbers using jQuery

I'm trying to figure out how to incorporate the jQuery validation plug-in into a multi-step form where validation occurs on each step as the user progresses. I know that typically, the validation plug-in is triggered by a submit request, but in this c ...

Create a fresh instance of an object in node.js by utilizing the require/new method

I am encountering a beginner problem with node.js where I cannot seem to create objects using the 'new' operator in the index.js file. My goal is to define a simple Person object within a Person.js file, located in the same directory as my index ...

Why isn't P5.JS's .display() working like it should?

I'm having trouble figuring out the scope of this code. I moved the function around, but I keep getting a "not a function" error. let bubbles = []; function setup() { createCanvas(400, 400); for (let i = 0; i < 10; i++){ bubbles[i] = new Bubbl ...

Tips on preventing repeated data fetching logic in Next.js App Routes

I'm currently developing a project with Next.js 13's latest App Routes feature and I'm trying to figure out how to prevent repeating data fetching logic in my metadata generation function and the actual page component. /[slug]/page.tsx expo ...

Accessing the locally stored data and displaying it in ng-bind

My journey to learn javascript through this project has hit a roadblock. I have stored an exchange rate in local storage: localStorage.gbpUSD = "1.42746"; Now, I want to utilize it instead of the hardcoded exchange rate in the code below... <input t ...

Is there a way to establish a connection with a secondary Firestore database in Node.js, allowing for the use of multiple Firestore databases

I have set up multiple firestore databases within my project. Using the command line, I created these databases and can view them in the Firestore Databases preview by following the instructions outlined here: https://cloud.google.com/blog/products/databas ...

Testing of onClick event in a React component using styled-components with Sinon spies

Utilizing sinon to test a react component and verify that an onClick function is triggered. Struggling to target the element to click on due to the use of styled-components. Encountering this error message: The "simulate" method should only be run on ...

The Next.js Link feature does not always guarantee that the component will render correctly, and the serverSideProps function may not always receive updated

Having an issue with next.js - when a user tries to navigate from one profile to another using the Link in the navbar: <li> <Link href={`/profile/${user.user.id}`}> <a className="flex flex-row items-center"> ...

Subcomponent in React is not rendering as expected

I have a primary React component with a subcomponent named AttributeInput. To prevent redundancy in my code, I moved some of the logic from the main component to a method within AttributeInput. My attempt at referencing this code looks like this: {this.s ...

Transforming a string into an object

I've been working on this code where my aim is to convert a string into an object and then display the data from an ajax call. However, it appears that using the string value in this way is not functioning as expected. var string = "first: 'Geor ...

What could be causing the <img src= ' '/> tag to malfunction in Express?

While learning about HTML, I noticed that simply using img src="...." worked fine. However, when working with Express, the same code did not work! The documentation mentioned that I needed to place the images in a folder named public, require(&ap ...

Managing data overload in Node.js can lead to Promise Rejection Warnings

I'm currently developing a feature where scanning a barcode adds the product information to a table. Once the data is in the table, there is a button to save it. Each row requires generating a unique stamp and inserting into tables named bo, bo2, and ...

Encountering weathers.map is not a function error while using React.js with OpenWeatherMap integration

Struggling with React.js for a college project and need some help. The error message I keep encountering is: weathers.map not a function I know it's probably something simple, but for the life of me, I can't figure it out! My project structure f ...

Execute multiple JavaScript files dynamically by utilizing the same npm run command

My directory structure: app Model user.js post.js Contents of my package.json file: "scripts": { "migrate": "node ./app/Model/" } I am looking to execute JavaScript files via command line in a dynamic manner. For example: npm run migr ...