Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the ChildrenCount of a child in Firebase using JavaScript

I have been doing this for an hour. I simply want to get the number of children in the child "Success" in the database below. The answers in similar stackoverflow questions are not working. I am new in Javascript Programming.

Database So far I have tried this

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

	})
})

and also this

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

	})
})

Where might I be going wrong.

like image 669
Martin Mbae Avatar asked Dec 24 '22 00:12

Martin Mbae


1 Answers

As explained in the doc, you have to use the numChildren() method, as follows:

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

If you want to use this method in a Cloud Function, you can do as follows:

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

Note that:

  1. The new syntax for Cloud Functions version > 1.0 is used, see https://firebase.google.com/docs/functions/beta-v1-diff?authuser=0

  2. You should not forget to return a promise or a value to indicate to the platform that the Cloud Function execution is completed (for more details on this point, you may watch the 3 videos about "JavaScript Promises" from the Firebase video series: https://firebase.google.com/docs/functions/video-series/).

like image 154
Renaud Tarnec Avatar answered Dec 26 '22 00:12

Renaud Tarnec