React Native Firebase:如何获取Tickets集合中所有文档及子Ticket信息并解决查询返回空数组问题?
Hey there, let's work through why you're getting an empty array when trying to pull data from your "Tickets" collection. Here are the most common fixes to try:
1. Double-Check Collection Name Case Sensitivity
Firestore is case-sensitive when it comes to collection names. You mentioned your collection is called "Tickets" (capital T), but your code uses collection("tickets") (lowercase t). That's likely the biggest issue! Make sure the name in your code matches exactly what's shown in the Firestore console.
2. Verify Your Firestore Security Rules
By default, Firestore blocks all read/write access to your database. If you haven't updated the rules, your app can't fetch any data.
For testing purposes, you can temporarily set open rules (but never leave this in production):
rules_version = '2'; service cloud.firestore { match /databases/{database}/documents { match /{document=**} { allow read, write: if true; // Only for testing! } } }
Once you confirm the data loads, replace this with proper rules that restrict access to authorized users only.
3. Include Document IDs in Your Results
Your current code only gets the document data, but you need the ticketID (which is the document's unique ID). Modify your map to include this ID:
firebase.firestore() .collection("Tickets") // Ensure this matches the exact collection name .get() .then(querySnapshot => { const tickets = querySnapshot.docs.map(doc => ({ ticketID: doc.id, // Capture the document ID as ticketID ...doc.data() // Spread the rest of the document's data })); console.log("Fetched tickets:", tickets); // Use the tickets array here to display your data }) .catch(error => { console.error("Error fetching tickets:", error); // Catch and log any hidden errors });
4. Add Error Handling to Debug
Adding a .catch() block will reveal if there's an underlying issue (like permission denied or misconfigured Firebase) causing the empty array. The code above includes this—check your console for any error messages that might point you to the problem.
5. Confirm Firebase is Properly Initialized
Make sure you've set up Firebase correctly in your React Native app. Here's a quick example of how that should look in your main app file (e.g., App.js):
import firebase from '@react-native-firebase/app'; import firestore from '@react-native-firebase/firestore'; // Initialize Firebase with your project config if (!firebase.apps.length) { firebase.initializeApp({ apiKey: "YOUR_API_KEY", authDomain: "YOUR_AUTH_DOMAIN", projectId: "YOUR_PROJECT_ID", // ... other required config fields }); } // Access Firestore once initialized const db = firestore();
Try these steps one by one, and you should be able to fetch your ticket data successfully!
内容的提问来源于stack exchange,提问作者Lele

