首页  >  问答  >  正文

尝试列出 Firestore 数据库的集合

<p>我想列出 Ionic4 应用程序内的 Firestore 数据库集合,因此我使用 listCollection 部分中的文档,因此我在代码中应用了示例代码:</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>这是我的构造函数:</p> <pre class="brush:php;toolbar:false;">constructor(private router: Router, private afs: AngularFirestore, private fireauth: AngularFireAuth) { }</pre> <p>我收到此错误:错误 TS2339:“Firestore”类型上不存在属性“listCollections”。</p> <p>我无法使用属性 listCollections,因为它位于在线文档中... </p>
P粉546179835P粉546179835420 天前514

全部回复(1)我来回复

  • P粉265724930

    P粉2657249302023-08-25 19:54:35

    实际上,如 Firestore JS SDK 文档 中所述,使用移动/网络客户端库无法检索集合列表

    这不仅适用于 Firestore 数据库的根集合,也适用于 Firestore 文档的子集合。

    但是,正如您在问题中提到的,可以使用 Cloud Firestore Node.js 客户端 API。因此,您可以使用 Cloud Function 来列出 Firestore 数据库的集合并从前端调用此云函数。

    由于您将从应用中调用此云函数,因此我们使用可调用云函数 .

    云函数代码

    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 };
    
    });

    前端代码

    要从 Angular 应用程序调用此可调用云函数,只需遵循 Angularfire 云函数文档

    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({ .... });
      }
    }

    请注意,此方法的灵感来自以下文章,介绍如何使用 JS SDK 列出 Cloud Firestore 文档的所有子集合。 (免责声明:我是作者)

    回复
    0
  • 取消回复