繁体   English   中英

如何列出 Firestore 文档的所有子集合?

[英]How to list all subcollections of a Firestore document?

在此处输入图片说明在此处输入图片说明

您好,我在从文档中下载所有集合时遇到问题。 我想在找到 id (userUid) 文档后能够下载它的所有集合,我需要每个集合的 id

export const getAllMessagesByUserId = async (userUid) => {
  const result = await firebase
    .firestore()
    .collection('messages')
    .doc(userUid)
    .onSnapshot((snapshot) => {
      console.log(snapshot);
    });

};

我写了一篇文章,提出了解决此问题的方法: 如何列出 Cloud Firestore 文档的所有子集合? 事实上,如Firestore 文档中所述,“使用移动/网络客户端库无法检索集合列表”。

我建议您使用文章中提出的第二种方法,即使用 Cloud Function。

这是从文章中复制的代码。

云功能:

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

});

从 Web 应用程序调用 Cloud Function 的示例:

  const getSubCollections = firebase
    .functions()
    .httpsCallable('getSubCollections');

  getSubCollections({ docPath: 'collectionId/documentId' })
    .then(function(result) {
      var collections = result.data.collections;
      console.log(collections);
    })
    .catch(function(error) {
      // Getting the Error details.
      var code = error.code;
      var message = error.message;
      var details = error.details;
      // ...
    });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM