2

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 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you Doug for the explanation.
0

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);
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.