从Firestore获取文档时是否包含内部集合?该如何获取?
Great question! Let's break this down clearly:
First off—no, when you fetch a document from Firestore, you don't automatically get any subcollections that might be nested under it. Firestore treats documents and subcollections as separate, independent resources. Subcollections aren't stored as fields within the parent document, so they won't be included in the data returned by docRef.get().
Now, if you need to access those subcollections, here are the two main ways to do it:
1. List all subcollections (if you don't know their names)
If you're working with a document and need to discover all its subcollections, use the listCollections() method on the document reference. This returns a promise that resolves to an array of collection references for each subcollection present.
Here's a JavaScript example:
const db = firebase.firestore(); const parentDocRef = db.collection('posts').doc('post_123'); parentDocRef.listCollections() .then(subcollections => { console.log(`Found ${subcollections.length} subcollections:`); subcollections.forEach(subcollection => { console.log(`- ${subcollection.id}`); // Now fetch documents from this subcollection subcollection.get().then(snapshot => { snapshot.forEach(doc => { console.log(` Document ${doc.id}:`, doc.data()); }); }); }); }) .catch(err => { console.error('Error listing subcollections:', err); });
2. Directly access a known subcollection
If you already know the name of the subcollection you want (like "comments" under a post document), you can reference it directly using the parent document's path. This is more efficient than listing all subcollections when you have prior knowledge of your database structure.
Example in JavaScript:
// Get the "comments" subcollection under post_123 const commentsRef = db.collection('posts/post_123/comments'); commentsRef.get() .then(snapshot => { if (snapshot.empty) { console.log('No comments found.'); return; } snapshot.forEach(doc => { console.log(`Comment ${doc.id}:`, doc.data()); }); }) .catch(err => { console.error('Error fetching comments:', err); });
Quick reminders:
- Listing subcollections doesn't incur any read charges, but fetching the documents inside those subcollections does count towards your Firestore usage.
- Subcollections can have their own nested subcollections too—you can keep chaining references (e.g.,
posts/post_123/comments/comment_456/replies) to access deeper levels.
Content of the question originates from Stack Exchange, question author Zhangir Siranov

