'Fetch some (and not all) properties from a list in Firebase Realtime Database

Suppose there is a list in my Realtime Database such that it has a user list at location userList as:

user1: { age: 20, name: john }

user2 : { age: 40, name: sam }

user3: { age: 30, name: cynthia }

Is there a way for me to write a query to fetch only the ages from the above userList?

I am currently using Angular 11, and taking help of Angular Fire package to communicate with the Firebase database.

Note: I have removed the apostrophes from the above example for clarity.



Solution 1:[1]

There's no direct method to so. You would have to fetch the complete node and then sort it out using Javascript manually. But if you want to fetch just one field then you can try this function which makes separate request for age of each user:

async function getAges() {
  const dbRef = firebase.database().ref("users")
  const requests = []

  const users = ["user1", "user2", "user3"]
  for (const user of users) {
    requests.push(dbRef.child(user).child("age").once("value"))
  }

  const snapshots = await Promise.all(requests)
  console.log(snapshots.map(snap => `${snap.ref.parent.key} -> ${snap.val()}`))
}

The output in console should be something like this:

enter image description here

Although you would need keys of all nodes i.e. the UIDs of all the users. If you have only UIDs stored somewhere then this method will be useful else to get the keys you need to fetch the complete users node.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dharmaraj