从Firestore提取数据时使用async forEach循环

时间:2018-11-05 06:05:35

标签: node.js firebase async-await google-cloud-firestore

我有一些类似的Firestore数据:

"Support": { "userid":"abcdxyz", "message": "hello" }

我正在使用nodejs来获取我的数据,我还想显示发送此消息的人的电子邮件地址和姓名。所以我正在使用以下功能:

database.collection("support").get().then(async function (collections) {
var data = [];
console.log("data collected");
collections.forEach(async function (collection) {
    var temp = {};
    var collectionData = collection.data()
    var userInfo = await getUserDetails(collectionData.userId)
    temp.name = userInfo.name
    temp.supportMessage = collectionData.supportMessage
    data.push(temp)
    console.log("data pushed")
});
    console.log("data posted")
    return res.status(200).end(JSON.stringify({ status: 200, message: "Support Message fetched successfully.", data: data }))
}).catch(error => {
    return res.status(500).end(JSON.stringify({ status: 500, message: "Error: " + error }))
});

以下是日志的顺序:收集的数据,发布的数据,推送的数据

我想要这样的顺序:收集的数据,推送的数据(x次),发布的数据

3 个答案:

答案 0 :(得分:1)

我在@estus评论的帮助下解决了我的答案。

信用:@estus

var data = [];
var tempCollection = [];
collections.forEach(collection => {
    tempCollection.push(collection.data());
});
for (collection of tempCollection) {
    var temp = {};
    var userInfo = await getUserDetails(collection.userId)
    temp.name = userInfo.name
    temp.supportMessage = collection.supportMessage
    data.push(temp)
}

它很容易解决了我的问题。

答案 1 :(得分:0)

使用以下代码:

database.collection("support").get().then(async function (collections) {
var data = [];
console.log("data collected");

for await(let collection of collections){
  var temp = {};
  var collectionData = collection.data()
  var userInfo = await getUserDetails(collectionData.userId)
  temp.name = userInfo.name
  temp.supportMessage = collectionData.supportMessage
  data.push(temp)
  console.log("data pushed")
}

console.log("data posted")
return res.status(200).end(JSON.stringify({ status: 200, message: "Support Message fetched successfully.", data: data }))
}).catch(error => {
  return res.status(500).end(JSON.stringify({ status: 500, message: "Error: " + error }))
});

OR

使用可以使用

var promise = Promise.all(collections.map((collection) =>{
   ...
   return await ... //or a promise
}));

promise.then(() => {
  console.log("posted");
  return res.status(200).end(...);
})

答案 2 :(得分:0)

我知道这可能不是 OP 的确切用例,但如果您有兴趣将集合查询的结果编译成数组,您仍然可以使用 .docsQuerySnapshot 属性来获取项目列表:

    ...
    const userId = <some-id>;
    const usersRef = db.collection(`users`)
    const usersSnapshot = await usersRef.where("id", "==", userId).get()

    if (usersSnapshot.empty) {
        console.log('found no matching user ', userId);
        return;
    }

    console.log(`found ${usersSnapshot.size} user records`);

    const userResults = []

    // this block here doesn't construct the results array before the return statement
    // because .foreach enumerator doesn't await: https://stackoverflow.com/q/37576685/1145905
    // usersSnapshot.forEach((doc) => {
    //     // doc.data() is never undefined for query doc snapshots
    //     //console.log(doc.id, " => ", doc.data());
    //     userResults.push[doc.data()];
    // });

    for (user of usersSnapshot.docs) {
        // console.log(user.id, " => ", user.data());
        userResults.push(user.data());
    }
    ...

更详细的example is here