【问题标题】:Get the ChildrenCount of a child in Firebase using JavaScript使用 JavaScript 在 Firebase 中获取孩子的 ChildrenCount
【发布时间】:2019-08-06 13:41:31
【问题描述】:

我已经这样做了一个小时。我只是想在下面的数据库中获取子“成功”中的子数。类似的 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);

	})
})

还有这个

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

	})
})

我可能哪里出错了。

【问题讨论】:

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


    【解决方案1】:

    正如doc中解释的那样,你必须使用numChildren()方法,如下:

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

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

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

    注意:

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

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

    【讨论】:

      【解决方案2】:
      const db = getDatabase(app)
      const questionsRef = ref(db, 'questions')
      
      const mathematicalLiteracy = child(questionsRef, 'mathematicalLiteracy')
      
      onValue(mathematicalLiteracy, (snapshot) => {
          const data = snapshot.val()
          const lenML = data.length - 1
          console.log(lenML)
      })
      

      这种方法对我有用。我想在我的数据库树中获取孩子们对mathematicalLiteracy 节点的计数。如果我使用.val() 获取它的值,它会返回一个数组,其中包含该节点的子节点和一个额外的空项。所以,我减去了一个空项目的计数。最后,我得到了我需要的孩子的数量。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-05-08
        • 1970-01-01
        • 2017-09-21
        • 2017-05-09
        • 2018-03-06
        • 2021-11-09
        相关资源
        最近更新 更多