【问题标题】:Get all documents in collection using Cloud Firestore使用 Cloud Firestore 获取集合中的所有文档
【发布时间】:2021-03-27 07:11:34
【问题描述】:

我阅读了几份文档,但我不明白为什么当我使用 Firebase (Cloud Firestore) 读取集合中的所有数据时,我应该在代码中使用额外的层 (foreach)。

这是原始文档:
https://firebase.google.com/docs/firestore/query-data/get-data#get_all_documents_in_a_collection

这是我的代码:

  async loadUsers(): Promise<User[]> {
    const users = new Array<User>();
    const snapshot = await this.firestore.collection('users').get();
    snapshot.forEach((collection) => {
      collection.docs.forEach(doc => {
        users.push(doc.data() as User);
      });
    });
    return users;
  }

据我了解,它应该像这样工作:

async loadUsers(): Promise<User[]> {
    const users = new Array<User>();
    const snapshot = await this.firestore.collection('users').get();
    snapshot.forEach(doc => {
      users.push(doc.data() as User);
    });
    return users;
  }

错误信息:
“'QuerySnapshot' 类型上不存在属性 'data'。”

【问题讨论】:

  • 我很困惑。您的第一个代码示例看起来并不正确。如果您要做的只是迭代集合中的文档,则不需要第二个 forEach 循环。第二个代码示例看起来正确。请编辑问题以更详细地解释什么不符合您的预期。
  • @DougStevenson 是的,你是对的,第一个代码示例看起来不太好,但它以某种方式工作,而第二个则没有。这就是我想了解的……为什么?

标签: node.js firebase google-cloud-firestore


【解决方案1】:

.collection().get() 不返回数组;它返回一个QuerySnapshot,它有一个property.docs,这是一个QueryDocumentSnapshot的数组,每个都有一个property.data,这是数据从文档中读取。

文档 https://firebase.google.com/docs/reference/js/firebase.firestore.CollectionReference

【讨论】:

    【解决方案2】:

    根据@LeadDreamer 的回答,我可以设法简化代码

      async loadUsers(): Promise<User[]> {
        const users = new Array<User>();
        await this.firestore.collection('users').get().subscribe(querySnapshot => {
          querySnapshot.docs.forEach(doc => {
            users.push(doc.data() as User);
          });
        });
        return users;
      }
    

    【讨论】:

      【解决方案3】:

      在新的模块化 firebase firestore(版本 9.+)中应该是这样的:

      import { getFirestore, collection, query, getDocs } from 'firebase/firestore/lite'
      async readAll() {
        const firestore = getFirestore()
        const collectionRef = collection(firestore, '/users')
        let q = query(collectionRef, orderBy('createTimestamp', 'desc'))
          
        const querySnapshot = await getDocs(q)
        const items = []
        querySnapshot.forEach(document => {
           items.push(document.data())
        })
        return items
      }
      

      我无法直接在querySnapshot 上找到任何类似于.docs 的参数,并且之前包含整个数组。所以它有点像 onSnapshot 过去和现在。

      【讨论】:

        猜你喜欢
        • 2021-05-09
        • 1970-01-01
        • 2020-08-08
        • 2020-04-16
        • 2021-07-01
        • 2018-04-03
        • 2018-03-15
        相关资源
        最近更新 更多