Retrieving all records in Firestore that have access to their child documents

I'm attempting to retrieve all the documents from each child collection (ratings) and update the average rating in the foobar document. However, I am encountering an error in one of my callable functions:

Unhandled error RangeError: Maximum call stack size exceeded
    at isLength (/srv/node_modules/lodash/lodash.js:11713:22)
    at isArrayLike (/srv/node_modules/lodash/lodash.js:11333:31)
    at keys (/srv/node_modules/lodash/lodash.js:13307:14)
    at /srv/node_modules/lodash/lodash.js:4900:21
    at baseForOwn (/srv/node_modules/lodash/lodash.js:2990:24)
    at Function.mapValues (/srv/node_modules/lodash/lodash.js:13400:7)
    at encode (/srv/node_modules/firebase-functions/lib/providers/https.js:183:18)
    at /srv/node_modules/lodash/lodash.js:13401:38
    at /srv/node_modules/lodash/lodash.js:4905:15
    at baseForOwn (/srv/node_modules/lodash/lodash.js:2990:24) 

Code:

const fooBarQuerySnapshot = await db
    .collection("foobars")
    .orderBy('ratingCount', 'desc')
    .get();

const fooBars = fooBarQuerySnapshot.docs
    .map(async (x: QueryDocumentSnapshot<DocumentData>) => {
        // fetch foo bar data
        const data = x.data();
        
        // get sub collection of ratings
        const ratingQuerySnapshot = await db
            .collection(collectionName)
            .doc(x.id)
            .collection('ratings')
            .get();
            
        // calculate average rating from the ratings subcollection
        data.avgRating = ratingQuerySnapshot.docs
             .map((y: QueryDocumentSnapshot<DocumentData>) => y.data().rating)
             .reduce((p, c) => p + c, 0) / data.ratingCount;
        return data;
    });

Answer №1

If you're seeing the error message

RangeError: Maximum call stack size exceeded
, it means that somewhere in your code, a function is being called repeatedly until it surpasses the call stack limit.

This issue often occurs because:

  • The Firestore API returns a DocumentSnapshot object with circular references to other objects, making it large and complex.

  • You're retrieving all ratingCount documents and then fetching all ratings documents for each ratingCount.

To resolve this, consider limiting the number of documents retrieved from the ratings collection. You can learn more about implementing limits in Firestore queries in this documentation. Process what you need to process and then handle the next batch of documents accordingly.

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

Creating a default option in a Select tag with React when iterating over elements using the map method

After learning that each element in the dropdown must be given by the Option tag when using Select, I created an array of values for the dropdown: a = ['hai','hello','what'] To optimize my code, I wrote it in the following ...

Is it possible to assign a type to an anonymous object in TypeScript?

Check out the code snippet below: hello({ name: "Michael" } as x) // <-- Except missing id here, but it doesn't type x = { id: string name: string } function hello(x: any) { console.log(x) } TS Playground No error is thrown de ...

The 'SVGResize' or 'onresize' property is not available on the 'SVGProps<SVGSVGElement>' type

Using React with SVG I'm facing an issue with handling the resizing event of an svg element. I have looked into using the SVGResize and onresize events, but encountered compilation errors when trying to implement them: const msg1 = (e: any) => co ...

Executing ts-node scripts that leverage imported CSS modules

Is there a way to execute scripts that utilize css modules? I am currently working on a typescript migration script that I would like to execute using ts-node. The ideal scenario would be to keep the script's dependencies separate from the React comp ...

This error is being thrown because the element has an implicit 'any' type due to the fact that a 'string' type expression cannot be used to index the 'Users' type

As I attempt to extract data from a json file and create an HTML table, certain sections of the code are functioning correctly while others are displaying index errors. All relevant files are provided below. This issue pertains to Angular. This is my json ...

Can you provide instructions on executing package dependencies using yarn in the command line? For example, is there a command similar to npx tsc init for initializing a npm

When utilizing yarn, the node_modules folder is not present. Instead, dependencies are stored in a .yarn/cache folder. I attempted to use yarn dlx tsc init and npx tsc init, but they did not achieve the desired result. There are various development depend ...

In order to iterate through a 'IterableIterator<number>', you must either enable the '--downlevelIteration' flag or set the '--target' to 'es2015' or newer

While attempting to enhance my Slider, I encountered an error when utilizing TypeScript React within this Next.js project: "Type 'IterableIterator' can only be iterated through when using the '--downlevelIteration' flag or with a ...

Issue with pre-selected default value in AngularJS TypeScript Kendo UI DropDownList

I have successfully implemented a list of objects for items, but now I am facing a challenge in adding a default selected value. Below is the HTML code for the drop-down: <select kendo-drop-down-list k-options="selectItems" k-ng-mode ...

Encountered an issue connecting Firebase with NextJs during build process

Recently delving into NextJS, I successfully created a project using Firebase. However, upon running "npm run build," an error has surfaced: @firebase/firestore: Firestore (X.X.X): Could not establish connection with Cloud Firestore backend. Backend faile ...

Using Angular 2 with the firebase-admin sdk

Whenever I attempt to integrate the firebase-admin SDK into my Angular2 project, an error occurs: ERROR in ./~/firebase-admin/lib/auth/token-generator.js Module not found: Error: Can't resolve 'jsonwebtoken' in '/home/koucky/git_projec ...

Adding custom type definitions for an untyped npm module in TypeScript 2

Despite attempting various methods recommended in other sources, I am struggling to configure a TypeScript project that utilizes an untyped NPM module. Below is a simplified example along with the steps I have taken. Let's imagine, for this demonstra ...

Having trouble with installing Typescript on a MacBook?

I have been attempting to follow the instructions provided on TypeScriptLang.org but for some reason, I am unable to successfully download typescript. This is what I have tried so far: mkotsollariss-MacBook-Pro:/ mkotsollaris$ which node /usr/local/bin/n ...

Getting content from a URL and storing it using Firebase Storage and Cloud Functions: a complete guide!

I have a real-time database where users can input the URL of an image. After triggering a cloud function upon creation/update, I am able to read the image's URL from the real-time database. Now, my goal is to download the image from the web (not uplo ...

Typescript is unable to access the global variables of Node.js

After using Typescript 1.8 with typings, I made the decision to upgrade to typescript 2.8 with @types. When I downloaded @types/node, my console started showing errors: error TS2304: Cannot find name 'require'. The project structure is as foll ...

Show the outcome stored within the const statement in TypeScript

I am trying to display the outcome of this.contract.mint(amount, {value: this.state.tokenPrice.mul(amount)}) after awaiting it. I want to see the result. async mintTokens(amount: number): Promise<void> { try { let showRes = await this.c ...

I attempted to make changes to a Firebase document using the update() function, however, the document did not reflect

I am currently in the process of creating a blog and have been focusing on implementing an edit post feature. However, I have encountered an issue where when I utilize the ref.update() method, it indicates that the update was successful but I do not see an ...

A loop in JavaScript/TypeScript that runs precisely once every minute

Here is a snippet of my code: async run(minutesToRun: number): Promise<void> { await authenticate(); await this.stock.fillArray(); await subscribeToInstrument(this, this.orderBookId); await subscribeToOrderbook(this, this.orderBookId ...

Implementing a global provider in Ionic 3

I have integrated a provider in my app that needs to stay active at all times while the application is running to monitor the network connection status. Following this guide, I included the class in my app.module.ts file to ensure it functions as a global ...

What is the process of creating an instance of a class based on a string in Typescript?

Can someone please guide me on how to create an instance of a class based on a string in Nestjs and Typescript? After conducting some research, I attempted the following code but encountered an error where it says "WINDOWS is not defined." let paul:string ...

Assigning object properties from a request to every item in an observable array of objects using RxJS

Despite my efforts to search various resources like mergeMap and switchMap, I am unable to solve the problem I'm facing as I am still new to RxJs. While I would like to provide more details about my attempts in this post, I fear it may complicate my q ...