Firebase get collection document data without running a forEach loop on querySnapshot

Viewed 1854

In firebase, when you get more than one document you need to loop through querySnaphot and run doc.data() to get each document data.

Is there a way to get all the documents data without looping every document result in the query, this looks quite expensive as an operation just to get what you would expect from a database query result.

2 Answers

The loop is not expensive. When you perform the query, the entire set of results is in memory in a QuerySnapshot object. You can use forEach() to iterate them, or you can simply iterate the docs array property. Either way is essentially the same speed. I suggest not being concerned about the loop at all - just make sure you request only the documents you need.

I know what you mean. All of this code to run one query:

import {  initializeApp, getFirestore, getAuth, signInWithEmailAndPassword, collection, getDocs, DocumentData, QueryDocumentSnapshot, query, Query, where } from 'firebase/firestore';

// init
const firebaseApp = initializeApp(config.firebase.prod.app);
const firestore = getFirestore(firebaseApp);
const firestoreAuth = getAuth(firebaseApp);
signInWithEmailAndPassword(firestoreAuth, config.firebase.prod.user.email, config.firebase.prod.user.password);
const stripeAccountColl = collection(firestore, "StripeAccount");

// Function
private async getStripeAccount(): Promise<FirebaseStripeAccountIntf> {
    try {
        const q1: Query<DocumentData> = query(this.stripeAccountColl, where("JobNumber", "==", "ABC123"));

        const querySnapshot: QuerySnapshot<DocumentData> = await getDocs(q1);

        return new Promise((resolve, reject) => {
            if (querySnapshot.size) {
                querySnapshot.forEach((doc: QueryDocumentSnapshot<DocumentData>) => {
                    const data: any = doc.data();
                    if (this.debug) {
                        console.debug(`getStripeAccount >> data = ${JSON.stringify(data)}`);
                    }
                    resolve(data);
                });
            } else {
                console.error(`getStripeAccount >> query returned no results`);
                reject("query returned no results");
            }
        });
    } catch (error: any) {
        console.error(`getStripeAccount >> error = ${error}`);
        throw new Error(error);
    }
}
Related