本文介绍了Firebase计数父亲的子数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取js firebase中父节点的子节点数。
我想要:

I'm trying to get the number of children for a parent node in js firebase.I'd like to have:

'user': {
    '-Yuna99s993m': { count: 1},
    '-Yada99s993m': { count: 2},
}

我正在创建一个云函数巫婆,每次输入一个新节点时,它应该添加等于用户节点的numChildren的计数。

I'm creating a cloud function witch every time a new node is entered it should add count equal to numChildren of user node.

exports.setCount = functions.database.ref('/user/{userId}').onWrite(event => {
    // This doesn't work
    const count = event.data.ref.parent.numChildren();
    return event.data.ref.update({ count });
});

有什么帮助才能让这个工作?

Any help to get this working?

谢谢。

推荐答案

调用 event.data.ref.parent.numChildren()将无效,因为 parent DatabaseReference ,而 numChildren() DataSnapshot 上定义(通过将监听器附加到引用来获得):

Calling event.data.ref.parent.numChildren() won't work, because parent is a DatabaseReference while numChildren() is defined on DataSnapshot (which you get by attaching a listener to a reference):

exports.setCount = functions.database.ref('/user/{userId}').onWrite(event => {
    return event.data.ref.parent.once("value", (snapshot) => {
      const count = snapshot.numChildren();
      return event.data.ref.update({ count });
    });
})

还有一个 Github回购,它完全符合您的要求:保持麻木的反击呃小孩该示例使用更有效的方法来保持计数。

There is also a child-count example in the functions-samples Github repo that does precisely what you want: keeping a counter of the number of children. That example uses a more efficient approach for keeping the count.

这篇关于Firebase计数父亲的子数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 05:12