node.js - 同步遍历 Firestore 集合
问题描述
我有一个 firebase 可调用函数,它对集合中的文档进行一些批处理。
步骤是
- 将文档复制到单独的集合中,将其归档
- 根据文档中的数据向第三方服务运行 http 请求
- 如果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);
}
});
}
解决方案
为了解决这个问题,我做了一个单独的函数调用,它返回一个我可以等待的承诺。我还利用了 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
推荐阅读
- php - 如果不存在数据,则显示大小为 0 的数组,而不是大小为 1 的数组 (array(1) { [0]=> string(0) "" }) || PHP
- django - 将已批准的电子邮件点编辑到 localhost
- php - PHP:如果发生异常则撤消
- swift - 通用可解码,无需解码
- python - 如何在 keras 中重塑一维卷积层的数据?
- javascript - 找不到带有角度路径的控件
- hibernate - Hibernate @ManyToOne 总是用referencedColumnName 加载实体
- r - 来自 R 代码块的动态 RMarkdown 标题
- charts - 在 Chart.js 中的图表内显示标签的总计(或简单地显示一个字符串)
- c++ - std::variant 的 std::vector 的内存布局如何?