首页 文章

Google Firestore - 如何在一次往返中通过多个ID获取文档?

提问于
浏览
32

我想知道是否可以通过往返Firestore的往返(网络呼叫)中的ID列表获取多个文档 .

7 回答

  • 0

    目前在Firestore中似乎不可能 . 我不明白为什么亚历山大的答案被接受,他提出的解决方案只返回“用户”集合中的所有文件 .

    根据您的需要,您应该考虑复制需要显示的相关数据,并在需要时仅请求完整的文档 .

  • 1

    当然,最好的方法是在 Cloud 功能中实现Firestore的实际查询?然后只有从客户端到Firebase的单程往返电话,这似乎是你要求的 .

    你真的希望保留所有的数据访问逻辑,就像这个服务器端一样 .

    在内部可能会有相同数量的对Firebase本身的调用,但它们都将跨越Google的超快速互连,而不是外部网络,再加上Frank van Puffelen所解释的流水线,您应该从这种方法 .

  • 8

    你可以使用这样的函数:

    function getById (path, id) {
      return firestore.getAll(
        [].concat(ids).map(id => firestore.doc(`${path}/${id}`)
      )
    }
    

    可以使用单个ID调用它:

    getById('collection', 'some_id')
    

    或一系列ID:

    getById('collection', ['some_id', 'some_other_id'])
    
  • 24

    如果你在Node中:

    https://github.com/googleapis/nodejs-firestore/blob/master/src/index.js#L533

    /**
    * Retrieves multiple documents from Firestore.
    *
    * @param {...DocumentReference} documents - The document references
    * to receive.
    * @returns {Promise<Array.<DocumentSnapshot>>} A Promise that
    * contains an array with the resulting document snapshots.
    *
    * @example
    * let documentRef1 = firestore.doc('col/doc1');
    * let documentRef2 = firestore.doc('col/doc2');
    *
    * firestore.getAll(documentRef1, documentRef2).then(docs => {
    *   console.log(`First document: ${JSON.stringify(docs[0])}`);
    *   console.log(`Second document: ${JSON.stringify(docs[1])}`);
    * });
    */
    
  • 0

    不,现在无法使用Cloud Firestore SDK批量处理多个读取请求,因此无法保证您可以一次读取所有数据 .

    然而正如Frank van Puffelen在上面的评论中所说,这并不意味着获取3个文档的速度是获取一个文档的3倍 . 在得出结论之前,最好先进行自己的测量 .

  • 0

    您可以做的最好是 not 使用 Promise.all 作为您的客户端然后必须等待 .all 读取才能继续 .

    迭代读取并让它们独立解析 . 在客户端,这可能归结为具有多个进度加载器映像独立解析为值的UI . 但是,这比冻结整个客户端要好,直到 .all 读取解析 .

    因此,立即将所有同步结果转储到视图,然后让异步结果在解析时单独进入 . 这可能看起来很小,但如果您的客户端连接不良(就像我目前在这家咖啡店那样),冻结整个客户端体验几秒钟可能会导致“这个应用程序很糟糕”的体验 .

  • 3

    在实践中,您将使用firestore.getAll这样

    async getUsers({userIds}) {
        const refs = userIds.map(id => this.firestore.doc(`users/${id}`))
        const users = await this.firestore.getAll(...refs)
        console.log(users.map(doc => doc.data()))
    }
    

    或者使用promise语法

    getUsers({userIds}) {
        const refs = userIds.map(id => this.firestore.doc(`users/${id}`))
        this.firestore.getAll(...refs).then(users => console.log(users.map(doc => doc.data())))
    }
    

相关问题