Home > Blockchain >  How to get value from firebase without the snapshot key [JS]
How to get value from firebase without the snapshot key [JS]

Time:12-20

Im trying to make friends system but in invite accept i have to delete invite of a guy in his list but i cant do it without the key.

Pic and what i have to get

How do i get the snapshot key by value (in this case uid) in database?

CodePudding user response:

Firebase Realtime Database queries work on single path, and then order/filter on a value at a fixed path under each direct child node. In your case, if you know whether the user is active or pending, you can find a specific value with:

const ref = firebase.database().ref("friends");
const query = ref.child("active").orderByValue().equalTo("JrvFaTDGV6TnkZq6uGMNICxwGwo2")
const results = query.get();
results.forEach((snapshot) => {
  console.log(`Found value ${snapshot.val()} under key ${snapshot.key}`)
})

There is no way to perform the same query across both active and pending nodes at the same time, so you will either have to perform a separate query for each of those, or change your data model to have a single flat list of users. In that case you'll likely store the status and UID for each user as a child property, and use orderByChild("uid").


Also note that using push IDs as keys seems an antipattern here, as my guess is that each UID should only have one status. A better data model for this is:

friends: {
  "JrvFaTDGV6TnkZq6uGMNICxwGwo2": {
    status: "active"
  }
}
  • Related