首页 > 解决方案 > Firestore join foreach map - 从两个集合中获取数据

问题描述

嘿,伙计们,我还需要你的帮助 :( 我不知道如何在 Firebase 中加入或做其他事情

我有两个集合:collection("guests") 有一个数据字段“Eventid”和一个数据字段“Userid”在第一步中我选择具有特定 Userid 的所有客人。所以我在 foreach 循环(或作为数组)中获取所有 Eventid!在第二个 Collection 集合('events')中,我选择所有信息并将其写入 JSON 文件。几次后这也有效,这是我的问题!我在函数中运行它,函数在加载事件之前返回。我不知道如何使用它,我尝试使用 await 和 async 或将其拆分为两个函数。Maybye 还有另一种实现方式。

db.collection("guests").where("userid", "==", id).get().then(function(querySnapshot) {
    querySnapshot.forEach(function (doc) {
        db.collection('events').doc(doc.data().eventid).get().then(function(doc) {
            if (doc.exists) {
                console.log(doc.id, " => ", doc.data());
            } else {
                console.log("No such document!");
            }
        }).catch(function(error) {
            console.log("Error getting document:", error);
        });
    });
});

   

标签: javascriptfirebasegoogle-cloud-firestoreforeachgoogle-cloud-functions

解决方案


我知道了!

exports.getEvent = functions.https.onRequest(async (req, res) => {
    console.log('==NACHEINANDER STARTEN==');
  
    const id = req.query.uid;
    var arr = [];
    var json = [];
    let query =  db.collection("guests").where("userid", "==", id);
    

await query.get().then(querySnapshot => {
        querySnapshot.forEach(documentSnapshot => {
            arr.push(documentSnapshot.data());
        });
    });
    //console.log(arr);
await processArray(arr)     


async function delayedLog(item) {
    await db.collection('events').doc(item.eventid).get().then(function(doc) {
        console.log(doc.data());
        json.push(doc.data());
    })

}

async function processArray(array) {
    const promises = array.map(delayedLog);
    // wait until all promises are resolved
    await Promise.all(promises);
    console.log('Done!');
 }


console.log("hello");


    res.status(200).send(JSON.stringify(json)); //, ...userData
});

推荐阅读