Steps for retrieving multiple documents from Firestore within a cloud function

In my cloud function, I have set up a trigger that activates on document write. This function is designed to check multiple documents based on the trigger and execute if/else statements accordingly.

I have developed a method that retrieves all documents using Promise.all, but I encountered an error when trying to access the document information if it is not yet available.


export function onTriggered(change, context) {
    const userPrevData = change.before.data();
    const userNewData  = change.after.data();

    const promises = [];

    // Get the uid
    const uid = context.params.userId;
    // User DocRef
    const userDoc        = firestoreInstance.collection('users').doc(uid).get();
    // User Session DocRef
    const userSessionDoc = firestoreInstance.collection('sessions').doc(uid).get();
    // Solution DocRef
    const solutionDoc    = firestoreInstance.collection('solution').doc('solutionId').get();

    promises.push(userDoc, userSessionDoc, solutionDoc);

    return Promise.all(promises).then((snapshots) => {
        // Use Promise.all with snapshot.docs.map to combine+return Promise context
        return Promise.all(snapshots.map((doc) => {
            // At this point, each document and their Ids print to the console.
            console.log('docId:::', doc.id);
            console.log('docData:::', doc.data());

            const solutionDocData = getSolutionDocData(doc);
            // This will print as 'undefined' until the correct document data is processed
            console.log('solutionDocData:::', solutionDocData);
            // This will print as 'undefined' until the correct document data is processed
            const clientSeed = doc.get('clientSeed');

            // Check to see if the Users' Guess is the same as the solution
            if (userNewData.guess.color === solutionDocData.guess.color && userNewData.guess.number === userNewData.guess.number) {
                console.log('User solution is correct');
            }

        }));

    })
}

function getSolutionDocData(doc) {
    if (doc.id === 'solutionId') { return doc.data(); }
}

Although I anticipate seeing 'User solution is correct' when the condition is met, I am encountering errors due to undefined data.

Answer №1

To resolve the issue, the logic was shifted to a .then() method.

    return Promise.all(promises).then((snapshots) => {
        // Utilizing Promise.all with snapshot.docs.map to merge and return Promise context
        return Promise.all(snapshots.map((doc) => {
            // All documents and their IDs are logged to the console at this stage.
            console.log('docId:::', doc.id);
            console.log('docData:::', doc.data());

            return doc.data();
        })).then(data => { 
        console.log('data:::', data);

        let userDocDetails = {};
        let userSessionDocDetails = {};
        let solutionDocDetails = {};

        data.forEach(document => {
            if (document.uid === uid)           { userDocDetails = document }
            if (document.serverSeedEncrypted)   { userSessionDocDetails = document }
            if (document.solutionId)            { solutionDocDetails = document }
        });


        });

    })

I'm uncertain if the order of the returned data will always match the original promise array sequence, so I used a forEach loop to identify unique properties and assign them 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

Button component in React remains visible until interacted with

https://i.stack.imgur.com/gTKzT.png I'm dealing with a sign out component in my app that requires me to click on it specifically to unselect any part of the application. This is implemented using React Material UI. <MenuItem onClick={e => this ...

What could be causing React to throw an invalid hook error when using useRoutes?

I encountered an error while attempting to add a new route to my project. import React from "react"; import News from "./NewsComponents/News"; import Photos from "./PhotosComponents/Photos"; import Contact from "./Contact"; import Home from "./Home"; ...

Sharing state between two functions in React using Hooks

Coming from a background in Vue, I am struggling to comprehend how to conditionally show something when the HTML is fragmented into different parts. Imagine having this structure: import React, { useState } from "react"; const [mobileNavOpen, setMobi ...

Remove all HTML tags except for those containing a specific class

Looking for a regex that removes all HTML tags except the "a" tags with the "classmark" class For example, given this HTML string: <b>this</b> <a href="#">not match</a> <a href="#" target="_blank" ...

What is causing the issue where Multiple file selection does not work when using the multiple attribute

I am having issues with uploading multiple files on my website. I have created an input field with the attribute multiple, but for some reason, I am unable to select multiple files at once. app.html <input type="file" (change)="onChange($event)" req ...

Is it possible to populate the blank cells in the weekday columns for previous and following months in a mat-datepicker or mat-calendar's display?

In order to enhance user experience, I am designing a calendar that allows users to select dates. My goal is to populate the empty cells at the beginning of the first week with dates from the previous and next months. For this project, I am utilizing the ...

Validation of forms on the client side using Angular in a Rails application

I'm facing an issue with implementing client-side validations for a devise registration form using Angular. Although I am able to add the "invalid" class to the fields as expected, I am struggling to get any output when using ng-show. There are no oth ...

Issues with the ionViewDidLoad() function?

Having some trouble implementing Email Authentication in my project. The method ionViewDidLoad is not being recognized. I also tried using the method ionViewWillLoad() but that didn't work either. Any ideas on what might be causing this issue? Here&a ...

How come ng-class doesn't apply to a specific class name?

I recently wrote the following code: <style> .dotted { border:dotted; } </style> .... <p ng-style="mystyle" ng-class="dotted">{{ answer }}</p> My intention was to have the paragraph element enclosed within a ...

Display embedded ng-template in Angular 6

I've got a template set up like this <ng-template #parent> <ng-template #child1> child 1 </ng-template> <ng-template #child2> child 2 </ng-template> </ng-template> Anyone know how t ...

Each time the page is reloaded, the Ajax call is triggered, resulting in duplicated

When I visit my homepage, one of the components on the page looks like this: import React, {Component} from 'react'; class BlogPostsWidget extends Component { render() { $.ajax({ type: "GET", url: 'https://example.com/wp- ...

Sharing package JSON file dependencies with child engines and addons in Ember.js

I am seeking information on how Ember Js can share the parent app's package.json file dependency (xyz:3.0.0) with child engines and addons without them needing to redeclare the dependencies in their own package.json files. This is to reduce the overal ...

What is the best way to utilize getInitialProps specifically during the building process of a NextJS site?

When I am developing a static site using NextJS, I need the getInitialProps method to run specifically during the build process and not when the client loads the page. During the build step, NextJS executes the getInitialProps method before generating the ...

karma - Plugin not located

Attempting to run JS test cases using karma, but consistently receiving a plugin not found error. Oddly enough, the same configuration file works perfectly for one of my co-workers. Below are the logs: $ karma start karma.conf.js 04 10 2016 17:51:24.755 ...

Troubleshooting issue with Angular2 Dart ngFor not refreshing view with WebSockets data stream

Recently, I've been facing an issue with an Angular2 component. Whenever I use websockets, the view fails to update properly. Interestingly, everything runs smoothly when I make http requests, but I really need to ensure that the data in the view stay ...

extract the ng-model data and send it to an angular directive

In my current project, I have a specific situation where there are multiple text-boxes and when any of them is clicked, the corresponding ng-model should be displayed in the browser console. To achieve this functionality, I came up with the following Angul ...

What is the method by which the asynchronous function produces the ultimate output?

Is there a way to modify a Dojo framework-created class with an asynchronous method so that it only returns the final value instead of a Promise or any other type? ...

Scroll-triggered Autoplay for YouTube Videos using JQuery

Issue: I'm trying to implement a feature where a YouTube video starts playing automatically when the user scrolls to it, and stops when the user scrolls past it. Challenges Faced: I am new to JavaScript web development. Solution Attempted: I referre ...

What advantages does utilizing Jasmine Spy Object provide in Angular Unit Testing?

I have a question regarding unit testing in Angular using Jasmin/Karma. Currently, I am working with three services: EmployeeService, SalaryService, and TaxationService. The EmployeeService depends on the SalaryService, which is injected into its constru ...

I am curious about how to implement overflow:hidden along with position:sticky in React.js

My attempt to address the white space issue caused by a navbar I created led me to try using overflow:hidden. The navbar is generated using the Header component, and I desired for it to have a position: sticky attribute. However, I realized that I cannot ...