gpt4 book ai didi

node.js - 创建新文档时触发功能不起作用

转载 作者:太空宇宙 更新时间:2023-11-03 23:56:18 25 4
gpt4 key购买 nike

我尝试了使用 Cloud Functions 的增量计数器示例 ( https://github.com/firebase/functions-samples/tree/master/child-count ),该示例引用实时数据库,但不引用 Firebase Firestore。

我正在关注 firestore 文档并尝试了一些更改。仍然面临问题,无法为 firestore 新文档运行此代码。我是第一次写云函数,我不确定我是否写对了。

   exports.countlikechange = functions.database.ref('/posts/{postid}/likes/{likeid}').onWrite(
async (change) => {
const collectionRef = change.after.ref.parent;
const countRef = collectionRef.parent.child('likes_count');

let increment;
if (change.after.exists() && !change.before.exists()) {
increment = 1;
} else if (!change.after.exists() && change.before.exists()) {
increment = -1;
} else {
return null;
}

// Return the promise from countRef.transaction() so our function
// waits for this async event to complete before it exits.
await countRef.transaction((current) => {
return (current || 0) + increment;
});
console.log('Counter updated.');
return null;
});

我想更新父文档中的计数。

最佳答案

您应该查看 documentation for Firestore triggers 。您正在编写的是实时数据库触发器,因为函数声明是functions.database。您需要使用functions.firestore来代替。您还使用实时数据库 API,而不是 Firestore API。使用 Firestore 的最终解决方案看起来与您现在的解决方案几乎完全不同。

关于node.js - 创建新文档时触发功能不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56946343/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com