【问题标题】:Firebase Cloud Function to count children sizeFirebase Cloud 函数来计算孩子的大小
【发布时间】: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


【解决方案1】:

这里出了很多问题。

从日志中可以看出,event.data.val 是一个函数。您需要调用 val() 从更改的位置获取 JavaScript 对象:event.data.val()

第二件事:当您已经知道要查询的位置的绝对路径时,不确定为什么要使用currentRef.parent.parent.child。您可以通过以下方式直接到达那里:

currentRef.root.ref(`/Uploads/Posts/${postID}/`)

第三件事,您在尝试使用变量插值来构建此字符串时使用单引号:/Uploads/Posts/{postID}/。为此,您需要使用反引号,并在其中使用 ${} 插入变量(您省略了 $)。

最后,您应该使用事务来执行写入,正如您在其他示例代码中看到的那样,因为两个函数完全有可能同时运行以尝试更改相同的位置。我不建议忽略它。

【讨论】:

  • 谢谢道格。这些反馈有所帮助。非常感谢!
猜你喜欢
  • 2018-04-27
  • 1970-01-01
  • 2016-10-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-01
  • 2012-08-30
  • 2020-03-19
相关资源
最近更新 更多