计算儿童对象

时间:2017-03-15 17:02:19

标签: javascript firebase firebase-realtime-database google-cloud-functions

看到firebase添加了功能,所以我一直在尝试使用它们..

以下是我的数据结构:

-feed1
  --child count = 0
  --childs
   ---1
   ---2
   ---3
-feed2
  --child count = 0
  --childs
   ---1
   ---2
   ---3
-feed3
  --child count = 0
  --childs
   ---1
   ---2
   ---3

我的目标是让每个Feed对象能够计算出每个孩子的子女数量。字段有一个更新子计数字段,每个字段有多少。

这是我到目前为止所做的...我通过添加一个子对象来测试它并且似乎没有触发该函数。我怀疑它与它的通配符元素有关,但无法真正弄清楚如何做到这一点

var functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

exports.countParent = functions.database.ref('{schoolid}/childs').onWrite(event => {
  return event.data.ref.parent().child('childCount').set(event.data.numChildren());
});

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

检查你的error logs in the Firebase Console,我打赌你会在那里看到错误。

Parent is a property, not a function

即使您修复了函数中的错误,也很容易出错。 numChildren()效率低下,您应该使用交易。

我为您的架构修改了Child Count example on Github的工作代码:

exports.countParent = functions.database.ref("{schoolid}/childs/{childid}").onWrite(event => {
  var collectionRef = event.data.ref.parent;
  var countRef = collectionRef.parent.child('childCount');

  return countRef.transaction(function(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;
    }
  });
});

这应该是一个很好的起点。

相关问题