【发布时间】:2018-05-27 23:08:58
【问题描述】:
按照firebase cloud functions API reference,我正在努力实现count increase/decrease:
Uploads/
- Posts/
- post_1
- post_2
...
- Likes/
- post_1/
- Number: 4
- post_2/
- Number: 2
...
还有,
exports.LikeCount= functions.database.ref('/Posts/{postID}').onWrite(event => {
const Ref = event.data.ref;
const postID = event.params.postID;
const likeCount= Ref.parent.parent.child('/Likes/' + postID + '/Number');
return likeCount.transaction(current => {
if (event.data.exists() && !event.data.previous.exists()) {
return (current || 0) + 1;
}else if (!event.data.exists() && event.data.previous.exists()) {
return (current || 0) - 1;
}
}).then(() => {
console.log("Done");
});
});
除位置外,与给出的示例相同。
它还给出another example,如果删除了喜欢的数量,那么它会重新计算喜欢的数量(孩子)。
这是我的版本(或至少是它的想法),它检查喜欢的数量,如果它小于 1,则重新计算它。 (只是因为如果喜欢的数量不存在,第一个函数会给出 1 而不管存在的喜欢的数量)。
exports.reCount= functions.database.ref('/Likes/{postID}/Number').onUpdate(event => {
const value = event.data.val;
//If the value is less than 1:
if (value <= 1) {
const currentRef = event.data.ref;
const postID = event.params.postID;
const postRef = currentRef.parent.parent.child('/Uploads/Posts/{postID}/');
return postRef.once('value')
.then(likeData=> currentRef.set(likeData.numChildren()));
}
});
使用第二个函数,我尝试使用以下内容获取 Number 值,其中 event.data.val 在 FB 日志中给出了 [Function: val],我认为我会在其中获得字符串值。
...和currentRef.parent.parent.child('/Uploads/Posts/{postID}/').numChilren(); 给了TypeError: collectionRef.numChildren is not a function。
我阅读了大量的在线教程和 API 参考,但仍然对为什么无法获取字符串值感到困惑。
我想我正在寻找一些可以借鉴的例子。
【问题讨论】:
-
我确实读过这个。我问的问题在链接中没有得到真正的回答。
-
除了“没有按预期工作”之外,您还有其他意见吗?
-
感谢您的回复。我在这些问题上花了很多钱。
标签: javascript firebase firebase-realtime-database google-cloud-functions