What is the best way to convert an array of Firestore DocumentReferences into an array of DocumentData?

Trying to create a Google Cloud Function that reads Firestore Documents from a collection and takes action based on these documents. The goal is to optimize efficiency by reading the documents once and storing them in an array to minimize read operations. However, I am facing challenges in ensuring that the iteration over my array starts only after completing the reading process.

export const matchUsers = functions
  .region("europe-west1")
  .pubsub
  .topic("matchUsers")
  .onPublish(async message => {
    console.log("Matching invoked...")

    await firebase.firestore().collection("matchData").listDocuments().then(docRefs => {
      const docs: admin.firestore.DocumentData[] = []

      docRefs.forEach(async docRef => {
        await docRef.get().then(snapshot => {
          const data = snapshot.data()
          if (data) {
            console.log("BPM: " + data.bpm)   # gets called
            docs.push(data)
          }
        })
      })

      console.log("Start loop")
      docs.forEach(doc => {
        console.log("BPM: " + doc.bpm)   # never gets called
      })
      console.log("Finish loop")

    })

  });

Expected Output:

Matching invoked...
BPM: 120
Start loop
BPM: 120
Finish loop

Answer №1

Give this a try:

const matchUsers = functions
  .region("europe-west1")
  .pubsub
  .topic("matchUsers")
  .onPublish(async message => {
    console.log("Initiating Match Users...")

    await firebase.firestore().collection("matchData").get().then(docRefs => {
      const docs: admin.firestore.DocumentData[] = []

      docRefs.forEach(docRef => {
        const data = docRef.data()
        console.log("BPM: " + data.bpm)   # getting printed
        docs.push(data)
      })

      console.log("Starting loop")
      docs.forEach(doc => {
        console.log("BPM: " + doc.bpm)
      })
      console.log("Loop finished")
    })

  });

You seem to be mixing asynchronous and synchronous operations, leading to unexpected behavior. Consider using get() for your needs.

Lastly, be cautious of timeouts if dealing with large collections.

Best of luck!

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

Ensuring the safety of generic types in Typescript

Typescript is known for its structured typing, which is a result of the dynamic nature of Javascript. This means that features like generics are not the same as in other languages with nominal type systems. So, how can we enforce type safety with generics, ...

Renaming personalized elements in Aurelia templates

My inquiry pertains to the process of aliasing custom elements and integrating them into aurelia's html-templates. To set the scene, I am utilizing the latest webpack typescript skeleton available at https://github.com/aurelia/skeleton-navigation and ...

Is there a function return type that corresponds to the parameter types when the spread operator is used?

Is it possible to specify a return type for the Mixin() function below that would result in an intersection type based on the parameter types? function Mixin(...classRefs: any[]) { return merge(class {}, ...classRefs); } function merge(derived: any, ... ...

Could someone teach me how to implement icon rotation in Vue.js using Vuetify?

I am currently working on adding a feature where the icon rotates when the button is clicked, moving from down to up and vice versa in a spinning motion. Here is the code I have so far: <template> <v-btn v-on:click="isShow = !isShow" ...

Troubleshooting: Issue with reloading in MERN setup on Heroku

I successfully deployed my MERN stack application on Heroku using the following code: import express from "express"; import path from "path"; const app = express(); const port = process.env.PORT || 5000; app.get("/health-check&qu ...

The colors of the active Svelte Carousel navigation dots do not smoothly transition along with the slides

Currently, I am developing a carousel feature using schadcn-svelte and embla carousel. Everything seems to work fine initially - when clicking on dot 2, it transitions smoothly from slide 1 to slide 2, and the active dot styles update correctly. However, a ...

What is the reason behind material-ui's decision to invoke their dialogs twice?

After attempting to implement a modal and realizing the strange behavior, I switched to using a dialog instead. To my surprise, the issue persisted. This is how I approached it: import Dialog, { DialogProps } from '@material-ui/core/Dialog'; imp ...

The Gulp task is stuck in an endless cycle

I've set up a gulp task to copy all HTML files from a source folder to a destination folder. HTML Gulp Task var gulp = require('gulp'); module.exports = function() { return gulp.src('./client2/angularts/**/*.html') .pipe( ...

Parent component interacting with child component

In my application, I have a header component along with registration and login components. The selector of the header component is used in both the login and registration components. There is also a button in the header that displays as a login button if t ...

Stop redux useSelector from causing unnecessary re-renders

I'm working on a component in React-Redux that utilizes the useSelector hook to retrieve a dictionary from the Redux store. This dictionary maps UUIDs to objects containing data that I need to display. interface IComponentProps { id: string } const ...

The specified target "TypeScriptClean" is not present within the project

I'm facing some issues in Visual Studio 2017 Professional. Despite not having any TypeScript code in my solution, I am encountering numerous TypeScript-related errors during the build process. The main error message that keeps popping up is: The targ ...

What is the best way to merge the results of several runs of an observable function

When working with Firestore, I need to retrieve multiple documents, each with a unique sourceAddressValue. This means for a list of N strings, I may need to fetch N documents. I attempted the following approach: getLocationAddresses(addresses: string[]) { ...

Implementing conditional properties in Typescript based on the value of another property

Is it possible to make a property required in a type based on the presence of another property? Here's an example: type Parent = { children?: Child[]; childrenIdSequence: string[]; // This property should only be required when `children` is prov ...

Troubleshooting the problem of redirecting a website to www on IIS 10 (Windows Server 2019)

I have a React website running on port 3000. Currently, the website can be accessed with and without the www prefix, causing duplicate SEO issues. I want to ensure that the website always redirects to https://www.pess.org.ua. web.config <?xml version=& ...

The property 'x' cannot be found when declaring two different return types

Consider this example: interface Dog { name: string } const likeDog = true const getDog = (): Dog | boolean => { const val = likeDog ? { name: 'fido' } : false return val } const myComponent = (): void => { const dog = getDog() ...

Clear out the existing elements in the array and replace them with fresh values

Within my Progressive Web App, I am utilizing HTTP requests to populate flip cards with responses. The content of the requests relies on the selected values. An issue arises when I choose an item from the dropdown menu. It triggers a request and displays ...

Converting Mesh to Object3D: A step-by-step guide

Currently utilizing Typescript alongside Webpack. To create a 3D floor using three.js, I have integrated multiple plane objects (100 in total) with a seamless image serving as their background: import { Scene, PerspectiveCamera, WebGLRenderer, ...

Struggling to properly import the debounce function in ReactJS when using TypeScript

I am facing an issue while trying to properly import the debounce library into my react + typescript project. Here are the steps I have taken: npm install debounce --save typings install dt~debounce --save --global In my file, I import debounce as: impo ...

Display popup when the form is submitted

Check out this Angular 4 component code designed for gathering contact details from website visitors: .html: <form (submit)="onCreateContact()"> <div class="form-group"> <input type="text" [(ngModel)]="contactname" name="contac ...

Unconventional way of assigning class properties in Typescript (Javascript): '?='

Recently, I came across the ?= assignment expression within a class property declaration. Can anyone provide some insight into what this means? I am familiar with the new Optional Chaining feature (object?.prop), but this particular syntax is unfamiliar t ...