Ionic 正在尝试列出Firestore数据库的集合

omhiaaxx  于 2022-12-08  发布在  Ionic
关注(0)|答案(1)|浏览(164)

我想列出Ionic4应用程序中Firestore数据库的集合,所以我在listCollection部分使用doc,所以我在代码中应用了示例代码:

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

下面是我构造函数:

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

我得到这个错误:错误TS2339:类型“Firestore”上不存在属性“listCollections”。
我无法使用属性listCollections,因为它在在线文档中...

envsm3lx

envsm3lx1#

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)

相关问题