Trying to list a collection of Firestore databases
P粉546179835
P粉546179835 2023-08-24 23:19:00
0
1
549
<p>I want to list a Firestore database collection inside an Ionic4 application, so I'm using the document from the listCollection section, so I've applied the sample code in my code: </p> <pre class="brush:php;toolbar:false;">this.afs.firestore.listCollections().then(collections => { for (let collection of collections) { console.log(`Found collection with id: ${collection.id}`); } });</pre> <p>This is my constructor: </p> <pre class="brush:php;toolbar:false;">constructor(private router: Router, private afs: AngularFirestore, private fireauth: AngularFireAuth) { }</pre> <p>I get this error: error TS2339: Property 'listCollections' does not exist on type 'Firestore'. </p> <p>I cannot use the attribute listCollections because it is in the online documentation... </p>
P粉546179835
P粉546179835

reply all(1)
P粉265724930

In fact, as documented in the Firestore JS SDK documentation , the collection list cannot be retrieved using the mobile/web client libraries.

This applies not only to the root collection of the Firestore database, but also to subcollections of Firestore documents.

However, as you mentioned in your question, it is possible to use the Cloud Firestore Node.js client API. Therefore, you can use a Cloud Function to list a collection of Firestore databases and call this cloud function from the frontend.

Since you will be calling this cloud function from your app, we use callable cloud function .

Cloud function code

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

admin.initializeApp();

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

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

    return { collections: collectionIds };

});

Front-end code

To call this callable cloud function from your Angular application, just follow the Angularfire Cloud Functions documentation.

import { Component } from '@angular/core';
import { AngularFireFunctions } from '@angular/fire/functions';

@Component({
  selector: 'app-root',
  template: `{ data$  | async }`
})
export class AppComponent {
  constructor(private fns: AngularFireFunctions) { 
    const callable = fns.httpsCallable('getCollections');
    this.data$ = callable({ .... });
  }
}

Note that this method is inspired by the following article on how to list all subcollections of a Cloud Firestore document using the JS SDK. (Disclaimer: I am the author)

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template