使用 JavaScript 在 Firebase 中获取孩子的 ChildrenCount

Mar*_*bae 4 javascript firebase firebase-realtime-database google-cloud-functions

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

数据库 到目前为止,我已经尝试过这个

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

	})
})
Run Code Online (Sandbox Code Playgroud)

还有这个

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

	})
})
Run Code Online (Sandbox Code Playgroud)

我可能哪里出错了。

Ren*_*nec 8

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

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

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

exports.children = functions.database
  .ref('/Success')
  .onWrite((change, context) => {
     console.log(change.after.numChildren());
     return null;
  });
Run Code Online (Sandbox Code Playgroud)

注意:

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

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