Getting total Number of User Items in Firebase Realtime database in javascript

Viewed 245

I have been trying to get amount of users that have same "referralId" in my firebase Realtime database,

users {
  AY35bkc5cbkufik8gfe3vjbmgr {
    email: james @gmail.com
    verify: none
    referralid: AY35ja35
  }
  B16fty9jDchfNgdx7Fxnjc5nxf5v {
    email: mobilewisdom @gmail.com
    verify: none
    referralid: AY35ja35
  }
}

How can I use JavaScript to count the amount of account with referralid:AY35ja35 I tried:

      const query = ref.orderByChild('referralid').equalTo('AY35ja35');
      query.get().then((results) => {
       console.log(Object.keys(results.val()).length);
      results.forEach((snapshot) => {
      console.log(snapshot.key, snapshot.val());
  });
});

But am getting this error in my console: Uncaught TypeError: query.get is not a function

2 Answers

Firstly you will have to run a query to get the data from firebase using either firebase package, axios or fetch

Your data is fetched in form of Object containing different objects. You can either user for .. in .. loop to iterate through the object.

var count = 0
for (const user in users) {
    if (user.referralid==="AY35ja35") {
       count++
    }
} 

Or use Object.values(object) function to get array of users. Now you can use a JavaScript array function such as map or filter.

by using map. you can do it like this:

var count=0
user.map(user=>{if(user.referralid==="AY35ja35"){count++})

or by using filter

const matchedUsers = user.filter(user=>(user.referralid==="AY35ja35"))
const count = matchedUsers.length

Hope this helps :)

In v8/namespaced syntax that'd be:

const ref = firebase.database().ref('users');
const query = ref.orderByChild('referralid').equalTo('AY35ja35');
const results = await query.get();
console.log(Object.keys(results.val()).length);
results.forEach((snapshot) => {
  console.log(snapshot.key, snapshot.val());
});

Or if you're in an environment where await doesn't work:

const ref = firebase.database().ref('users');
const query = ref.orderByChild('referralid').equalTo('AY35ja35');
query.get().then((results) => {
  console.log(Object.keys(results.val()).length);
  results.forEach((snapshot) => {
    console.log(snapshot.key, snapshot.val());
  });
});

In v9/modular syntax the equivalent would be:

const ref = ref(getDatabase(), 'users');
const query = query(ref, orderByChild('referralid'), equalTo('AY35ja35'));
const results = await get(query);
console.log(Object.keys(results.val()).length);
results.forEach((snapshot) => {
  console.log(snapshot.key, snapshot.val());
});

Or if you're in an environment where await doesn't work:

const ref = ref(getDatabase(), 'users');
const query = query(ref, orderByChild('referralid'), equalTo('AY35ja35'));
get(query).then((results) => {
  console.log(Object.keys(results.val()).length);
  results.forEach((snapshot) => {
    console.log(snapshot.key, snapshot.val());
  });
});
Related