使用JavaScript获取Firebase中孩子的ChildrenCount

时间:2019-03-15 13:01:49

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

我已经做了一个小时。我只想在下面的数据库中获取子级“成功”中的子级数。类似的stackoverflow问题中的答案不起作用。我是Java语言编程的新手。

Database 到目前为止,我已经尝试过

var children = firebase.database().ref('Success/').onWrite(event => {
	return event.data.ref.parent.once("value", (snapshot) => {
		const count = snapshot.numChildren();
console.log(count);

	})
})

还有这个

var children = firebase.database().ref('Success/').onWrite(event => {
	return event.data.ref.parent.once("value", (snapshot) => {
		const count = snapshot.numChildren();
console.log(count);

	})
})

我可能要去哪里了

1 个答案:

答案 0 :(得分:2)

doc中所述,您必须使用numChildren()方法,如下所示:

os.system('cls')

如果要在Cloud Function中使用此方法,可以执行以下操作:

var ref = firebase.database().ref("Success");
ref.once("value")
  .then(function(snapshot) {
    console.log(snapshot.numChildren()); 
  });

请注意:

  1. 使用了Cloud Functions版本> 1.0的新语法,请参见https://firebase.google.com/docs/functions/beta-v1-diff?authuser=0

  2. 您不应忘记向平台返回一个承诺或值,以指示Cloud Function执行已完成(有关这一点的更多详细信息,您可以从以下网址观看3个有关“ JavaScript Promises”的视频: Firebase视频系列:https://firebase.google.com/docs/functions/video-series/)。