首页 > 解决方案 > 在 Firestore 中获取文档集合

问题描述

这是我的 Firebase 数据库

- conversations (collection)
-- xxx (document)
--- users (collection)
---- xxx (document)

我想列出所有对话及其用户

this.db.collection('conversations').get().then(querySnapshot => {
    querySnapshot.docs.forEach(doc => {
        console.log(doc.collection('users').get())
    });
});

我得到 doc.collection 不是函数

更新:这是我在获得 id 并进行新查询后所拥有的。现在的问题是。这是高性能的吗?

    this.db.collection('conversations').get().then(conversationsQuerySnapshot => {
        conversationsQuerySnapshot.docs.forEach(doc => {
            this.db.collection('conversations').doc(doc.id).collection('users').get().then(usersQuerySnapshot => {
                usersQuerySnapshot.docs.forEach(doc => {
                    console.table(doc.data());
                });
            });
        });
    });

标签: javascriptgoogle-cloud-firestore

解决方案


您正在寻找doc.ref.collection('users'),因为您需要从DocumentSnapshot到其DocumentReference通过doc.ref

请注意,我发现通过简单地遵循类型最容易发现此类错误。你querySnapshot是一个QuerySnapshot,这意味着你doc是一个QueryDocumentSnapshot。由于QueryDocumentSnapshot没有collection方法,因此更容易找出问题所在。


推荐阅读