【发布时间】:2019-07-09 06:16:35
【问题描述】:
我已尝试使用 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;
});
我想更新父文档中的计数。
【问题讨论】:
标签: node.js google-cloud-firestore google-cloud-functions