我有一个 firestore 集合,他的值之一是文档 ID 数组。
我需要检索所有集合项以及存储在数组 id 中的所有文档。
这是我收藏的结构
我的代码:
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/