Hammas Ali
Hammas Ali

Reputation: 604

Fetch every subcollection of a currentUser document in flutter firestore

What I want is to fetch all the subCollections in the current user document. What will be the implementation method? These subcollection contains further documents which contains data. I just want to fetch the subcollection so that I can display user to whom the current user have messaged(Not the chat/data inside document).

Firestore Data Structure

enter image description here

Upvotes: 0

Views: 246

Answers (1)

Renaud Tarnec
Renaud Tarnec

Reputation: 83103

From your print screen, it seems that the subcollection names are created on the fly, i.e. you don't know them upfront.

With the Client SDKs (including the Flutter plugin) there is no method which allows listing the subcollection of a document. See the doc: "Retrieving a list of collections is not possible with the mobile/web client libraries".

Here are two common workarounds:

  1. Save the names of the subcollections in a field of the parent doc, e.g. a field of type Array. You then need to query the parent doc, read the value of this field, iterate on the array elements and query each subcollection.
  2. Use the Admin SDK which offers a method to list subcollections of a Firestore document. You can write a Callable Cloud Function that you would call from your Flutter app.

This following article details those two approaches with code examples (in particular the full code for the Callable Cloud Function, which I paste below).

const functions = require('firebase-functions');
const admin = require('firebase-admin');

admin.initializeApp();

exports.getSubCollections = functions.https.onCall(async (data, context) => {

    const docPath = data.docPath;

    const collections = await admin.firestore().doc(docPath).listCollections();
    const collectionIds = collections.map(col => col.id);

    return { collections: collectionIds };

});

Upvotes: 2

Related Questions