首页 > 解决方案 > 同步遍历 Firestore 集合

问题描述

我有一个 firebase 可调用函数,它对集合中的文档进行一些批处理。

步骤是

  1. 将文档复制到单独的集合中,将其归档
  2. 根据文档中的数据向第三方服务运行 http 请求
  3. 如果2成功,删除文档

我无法强制代码同步运行。我无法弄清楚正确的等待语法。

async function archiveOrders  (myCollection: string) {

//get documents in array for iterating
const currentOrders = [];
console.log('getting current orders');
await db.collection(myCollection).get().then(querySnapshot => {
    querySnapshot.forEach(doc => {
        currentOrders.push(doc.data());
    });
});

console.log(currentOrders);

//copy Orders
currentOrders.forEach (async (doc) => {

    if (something about doc data is true ) {
        let id = "";
        id = doc.id.toString();
        await db.collection(myCollection).doc(id).set(doc);
        console.log('this was copied: ' + id, doc);
    }

});

}

标签: node.jstypescriptfirebasegoogle-cloud-firestore

解决方案


为了解决这个问题,我做了一个单独的函数调用,它返回一个我可以等待的承诺。我还利用了 QuerySnapshot,它返回此 QuerySnapshot 中所有文档的数组。请参阅此处了解用法。

// from inside cloud function
// using firebase node.js admin sdk

const current_orders = await db.collection("currentOrders").get();

for (let index = 0; index < myCollection.docs.length; index++) {
  const order = current_orders.docs[index];
  await archive(order);
}


async function archive(doc) {

    let docData = await doc.data();

if (conditional logic....) {
    try {
      // await make third party api request
      await db.collection("currentOrders").doc(id).delete();

    }
    catch (err) {
      console.log(err)
    }
} //end if

} //end archive

推荐阅读