ste*_*Kim 0 javascript firebase firebase-realtime-database google-cloud-functions
在firebase云功能API参考之后,我试图实现计数增加/减少:
Uploads/
- Posts/
- post_1
- post_2
...
- Likes/
- post_1/
- Number: 4
- post_2/
- Number: 2
...
Run Code Online (Sandbox Code Playgroud)
和,
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");
});
});
Run Code Online (Sandbox Code Playgroud)
除了位置之外,它与给出的示例相同.
它还给出了另一个例子,如果删除了喜欢的数量,那么它会重新计算喜欢(儿童)的数量.
这是我的版本(或至少它的想法),它检查喜欢的数量,如果它小于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()));
}
});
Run Code Online (Sandbox Code Playgroud)
使用第二个函数,我试图Number
使用以下在FB日志中event.data.val
给出的值来获取值[Function: val]
,我认为我会得到字符串值.
......并且currentRef.parent.parent.child('/Uploads/Posts/{postID}/').numChilren();
给了TypeError: collectionRef.numChildren is not a function
.
我阅读了大量的在线教程和API参考,但仍然有点困惑,为什么我不能得到字符串值.
我想我正在寻找一些可以解决的例子.
这里出了很多问题.
从日志中可以看出,event.data.val
是一个功能.您需要调用val()从更改的位置获取JavaScript对象:event.data.val()
第二件事:currentRef.parent.parent.child
当你已经知道要查询的位置的绝对路径时,不确定为什么要使用它.你可以直接到达那里:
currentRef.root.ref(`/Uploads/Posts/${postID}/`)
Run Code Online (Sandbox Code Playgroud)
第三件事,你在使用单引号看起来像尝试使用变量插值来构建这个字符串:/Uploads/Posts/{postID}/
.你需要为此使用反引号,并在其中使用$ {}来插入变量(你省略了$).
最后,您应该使用事务来执行写操作,正如您在其他示例代码中看到的那样,因为两个函数完全可以同时运行以尝试更改相同的位置.我不建议把它留下来.
归档时间: |
|
查看次数: |
633 次 |
最近记录: |