Trying to list collection of Firestore Database

房东的猫 提交于 2020-02-16 00:25:41

问题


I'd like to list of the collection of Firestore database inside Ionic4 app so I use the doc in the section listCollection so I applied the example code in my code :

this.afs.firestore.listCollections().then(collections => {
  for (let collection of collections) {
    console.log(`Found collection with id: ${collection.id}`);
  }
});

here is my constructor :

  constructor(private router: Router,
              private afs: AngularFirestore,
              private fireauth: AngularFireAuth) { }

And I get this error : error TS2339: Property 'listCollections' does not exist on type 'Firestore'.

I can not use the property listCollections whereas it is in the online doc...


回答1:


Actually, as detailed in the Firestore JS SDK documentation, retrieving a list of collections IS NOT possible with the mobile/web client libraries.

This is true for the roots collections of your Firestore database but also for the sub-collections of a Firestore document.

However, as you have mentioned in your question, it IS possible with the Cloud Firestore Node.js Client API. Therefore you can use a Cloud Function to list the collections of your Firestore DB and call this Cloud Function from your front-end.

Since you will call this Cloud Function from your app we use a 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 app, just follow the Angularfire documentation for Cloud Functions.

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 approach is inspired from the following article, which describes how to list all subcollections of a Cloud Firestore document with the JS SDK. (Disclaimer: I'm the author)



来源:https://stackoverflow.com/questions/58993098/trying-to-list-collection-of-firestore-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!