Home >Web Front-end >JS Tutorial >How to List Subcollections in Cloud Firestore: Client vs. Server-Side Approaches?
In Cloud Firestore, documents can have subcollections, which are essentially collections that are nested within a document. To retrieve the names of the subcollections within a document, there are different approaches depending on whether you're using a client-side or server-side SDK.
Client-side SDKs
In client-side SDKs (e.g., web, iOS, Android), getting a list of subcollection names is currently not supported. According to the Firestore documentation:
Retrieving a list of collections is not possible with the mobile/web client libraries. You should only look up collection names as part of administrative tasks in trusted server environments. If you find that you need this capability in the mobile/web client libraries, consider restructuring your data so that subcollection names are predictable.
Server-side SDKs
On the other hand, server-side SDKs provide methods to retrieve subcollection names. For example, in the Node.js SDK, you can use the listCollectionIds method:
const {Firestore} = require('@google-cloud/firestore'); const firestore = new Firestore(); const documentRef = firestore.doc('rootCollection/aDocument'); documentRef.listCollections().then((collections) => { const subcollectionNames = collections.map(collection => collection.id); console.log(subcollectionNames); // ['subCollection1', 'subCollection2'] });
Other options
If you need to retrieve subcollection names in a client-side environment, you could consider the following alternative approaches:
The above is the detailed content of How to List Subcollections in Cloud Firestore: Client vs. Server-Side Approaches?. For more information, please follow other related articles on the PHP Chinese website!