Firebase Functions(TypeScript)中QuerySnapshot无map属性问题求助
Hey there! Let's break down why you're hitting this error and fix it step by step.
What's Causing the Error?
The core issue here is that you're trying to call map() directly on a Promise returned by Firestore's get() method, instead of waiting for the Promise to resolve to the actual QuerySnapshot object.
Firestore's collection().get() returns a Promise<QuerySnapshot> — this is just a placeholder for the future result, not the actual data set. The map() method doesn't exist on Promises, only on arrays like the docs array inside a resolved QuerySnapshot.
RxJS won't solve this because you're working with Promises (not Observables) by default in Firebase Functions, and introducing RxJS here is unnecessary complexity for this use case.
Correct Data Fetching with async/await
Here's how to properly fetch and process data from Firestore using async/await in TypeScript:
Step 1: Await the Promise to get the QuerySnapshot
First, use await to wait for the get() call to resolve. This gives you access to the actual QuerySnapshot instance with the data you need.
Step 2: Use snapshot.docs to access the document array
The QuerySnapshot has a docs property that's an array of DocumentSnapshot objects. This is the array you can call map() on to transform your data.
Example Code
import * as functions from "firebase-functions"; import * as admin from "firebase-admin"; admin.initializeApp(); const db = admin.firestore(); // Example HTTP Function to fetch collection data export const fetchCollectionData = functions.https.onRequest(async (req, res) => { try { // ✅ Await the Promise to resolve to QuerySnapshot const querySnapshot = await db.collection("your-collection-name").get(); // ✅ Map over the docs array from the resolved QuerySnapshot const dataArray = querySnapshot.docs.map((doc) => ({ id: doc.id, // Include document ID if needed ...doc.data(), // Spread the document's raw data })); res.status(200).json(dataArray); } catch (error) { functions.logger.error("Error fetching data:", error); res.status(500).send("Failed to fetch data"); } });
Additional Tips
- If you're fetching a single document (using
doc().get()), it returns aPromise<DocumentSnapshot>. You'll still need to await it, then check if the document exists before accessing its data:const docSnapshot = await db.collection("your-collection").doc("target-doc-id").get(); if (docSnapshot.exists) { const docData = docSnapshot.data(); // Process the single document data here } - Always wrap your async code in a
try/catchblock to handle errors gracefully in Firebase Functions — this ensures your function doesn't crash unexpectedly and returns meaningful error messages.
Hope this clears up the confusion and fixes your error! Let me know if you run into any other snags.
内容的提问来源于stack exchange,提问作者pb4now

