![](/img/trans.png)
[英]Nextjs getStaticPaths not fetching data from firebase firestore
[英]Fetching Firebase Firestore References
假設我有以下 Firestore 數據結構:
tickets
{
name: "Testticket",
open: true,
users: [
"users/abcdefg1234" // Firestore reference
]
}
收藏users
{
name: "John Doe",
color: "green"
}
我的目標是獲取所有open
為真的門票,包括用戶 object 而不是參考。
目前我正在這樣做:
// Firebase Functions node.js code
async function getUserData(item) {
const queryResult = await item.get();
return await queryResult.data();
}
exports.getOpenTickets = async (request, response) => {
const query = await db.collection("tickets").where("open", "==", true).get();
let tickets = [];
query.forEach(async (doc) => {
let data = doc.data();
console.log("data", data);
data.userObjects = await Promise.all(data.users.map(getUserData));
console.log("data.userObjects", data.userObjects);
tickets.push(data);
});
return response.json(tickets);
};
問題:用戶數據已獲取,但主 function 並未等待(已通過控制台日志語句進行檢查)。
這是我的 node.js 控制台日志:
i functions: Beginning execution of "api"
! Google API requested!
- URL: "https://oauth2.googleapis.com/token"
- Be careful, this may be a production service.
> data {
> open: true,
> name: 'Testticket',
> users: [
> DocumentReference {
> _firestore: [Firestore],
> _path: [ResourcePath],
> _converter: [Object]
> }
> ]
> }
i functions: Finished "api" in 1069.554ms
> data.userObjects [ { color: 'green', name: 'John Doe' } ]
如何解決這個問題?
如果你想在一個循環中運行異步操作,那么你不應該使用forEach
。 嘗試使用for of
循環重構代碼,如下所示:
exports.getOpenTickets = async (request, response) => {
const snap = await db.collection("tickets").where("open", "==", true).get();
let tickets = [];
for (const doc of snap.docs ) {
let data = doc.data();
console.log("data", data);
data.userObjects = await Promise.all(data.users.map(getUserData));
console.log("data.userObjects", data.userObjects);
tickets.push(data);
}
return response.json(tickets);
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.