node.js - 从 id 数组中获取 firestore 文档列表

标签 node.js typescript firebase google-cloud-firestore google-cloud-functions

我有一个 firestore 集合,他的值之一是文档 ID 数组。
我需要检索所有集合项以及存储在数组 id 中的所有文档。
这是我收藏的结构
enter image description here

我的代码:

export const getFeaturedMixes = functions.https.onRequest((request, response) => {
    let result:any[] = []
    featuredMixes.get().then(mixesSnap => {

        mixesSnap.forEach(doc => {
            let docId = doc.id
            let ids = doc.data().tracks

            let resultTracks:any[] = []
            ids.forEach(id => {
                let t = tracksCollection.doc(id.track_id).get()
                resultTracks.push({'id' : id.track_id, 'data': t})
            })
            result.push({'id':docId, 'tracks': resultTracks})
        })
        return result
    })
    .then(results => {
        response.status(200).send(results)
    }).catch(function(error) {
        response.status(400).send(error)
    })
});

我得到这个回复:
{
        "id": "Xm4TJAnKcXJAuaZr",
        "tracks": [
            {
                "id": "FG3xXfldeJBbl8PY6",
                "data": {
                    "domain": {
                        "domain": null,
                        "_events": {},
                        "_eventsCount": 1,
                        "members": []
                    }
                }
            },
            {
                "id": "ONRfLIh89amSdcLt",
                "data": {
                    "domain": {
                        "domain": null,
                        "_events": {},
                        "_eventsCount": 1,
                        "members": []
                    }
                }
            }
    ]
}

响应不包含文档数据

最佳答案

get() 方法是异步的并返回一个 Promise。因此,您不能执行以下操作:

 ids.forEach(id => {
      let t = tracksCollection.doc(id.track_id).get()
      resultTracks.push({'id' : id.track_id, 'data': t})
 })

您需要等待 get() 返回的 Promise方法解析,才能使用t (这是一个 DocumentSnapshot )。

为此,由于您想并行获取多个文档,您需要使用 Promise.all() .

以下应该可以解决问题。请注意,它没有经过测试,您仍然可以轻松完成代码的一部分,请参阅最后的注释。如果您在最终确定时遇到一些问题,请将您的新代码添加到您的问题中。
export const getFeaturedMixes = functions.https.onRequest((request, response) => {
    let result: any[] = []

    const docIds = [];

    featuredMixes.get()
        .then(mixesSnap => {


            mixesSnap.forEach(doc => {
                let docId = doc.id
                let ids = doc.data().tracks

                const promises = []

                ids.forEach(id => {
                    docIds.push(docId);
                    promises.push(tracksCollection.doc(id.track_id).get())
                })

            })

            return Promise.all(promises)
        })
        .then(documentSnapshotArray => {

            // Here documentSnapshotArray is an array of DocumentSnapshot corresponding to
            // the data of all the documents with track_ids

            // In addition, docIds is an array of all the ids of the FeaturedMixes document

            // IMPORTANT: These two arrays have the same length and are ordered the same way

            //I let you write the code to generate the object you want to send back to the client: loop over those two arrays in parallel and build your object


            let resultTracks: any[] = []

            documentSnapshotArray.forEach((doc, idx) => {
                // .....
                // Use the idx index to read the two Arrays in parallel

            })

            response.status(200).send(results)

        })
        .catch(function (error) {
            response.status(400).send(error)
        })
});

关于node.js - 从 id 数组中获取 firestore 文档列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61929775/

相关文章:

javascript - Node.js 缓冲区和二进制文件

node.js - 如何优化 firebase 函数的响应速度

ios - Firebase 加载相关数据 iOS

firebase - Firestore - 查询数组字段中对象的过滤器位置

ios - 编译错误 : kFirLoggerSwizzler refrenced from

node.js - 使用 NGINX 代理的多个 Node.js 服务器

javascript - 使用 Jade 变量附加环境变量

typescript - 类型在其自己的 'then' 方法的履行回调中被直接或间接引用

typescript - 如何使用一个可观察对象的输出来过滤另一个

typescript - 使用参数或泛型来约束另一个参数的类型?