为 firebase firestore 编写基于事件的云函数时,通常会更新受影响文档中的字段,例如:
当更新用户集合的文档时,将触发一个函数,假设我们要确定用户信息状态,并且我们有一个 completeInfo: boolean
属性,如果我们不使用像 needsUpdate: boolean
这样的标志,函数将不得不执行另一个更新,以便触发器再次触发。为了确定是否执行该函数,我们将有一个无限循环。
有没有其他方法可以解决这种行为?或者这种情况是数据库设计方式的结果?我们怎么能避免在这种情况下结束?
最佳答案
我有一些转换数据的 Cloud Functions 常用方法:
onCreate
我确保我的代码只运行一次,即使它最终更新了新创建的文档。 最近的一个例子是我更新文档中的金额,然后需要将其分发给所有用户:
exports.fanoutAmount = functions.firestore.document('users/{uid}').onWrite((change, context) => {
let old_amount = change.before && change.before.data() && change.before.data().amount ? change.before.data().amount : 0;
let new_amount = change.after.data().amount;
if (old_amount !== new_amount) {
// TODO: fan out to all documents in the collection
}
});
关于firebase - 编写云函数时如何避免循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55887753/