How to Get the Key from the Value in Firebase

How to get the key from the value in firebase

That's because you're using a ValueEventListener. If the query matches multiple children, it returns a list of all those children. Even if there's only a single matches child, it's still a list of one. And since you're calling getKey() on that list, you get the key of the location where you ran the query.

To get the key of the matches children, loop over the children of the snapshot:

mDatabase.child("clubs")
.orderByChild("name")
.equalTo("efg")
.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
String clubkey = childSnapshot.getKey();

But note that if you assume that the club name is unique, you might as well store the clubs under their name and access the correct one without a query:

mDatabase.child("clubs")
.child("efg")
.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
String clubkey = dataSnapshot.getKey(); // will be efg

Get Key Value Given Other Key Value in FireBase

I recommend using a query to perform the filtering on the server, instead of downloading the entire users node and filtering in your application code as you now do.

var givenEmail = "email2@gmail.com";

var dataRef = firebase.database().ref('users');
var query = dataRef.orderByChild('email').equalTo(givenEmail);
dataRef.once('value', (snapshot) => {
snapshot.forEach((userSnapshot) => {
console.log(userSnapshot.val().id);
});
});

How do I get the key of a value in FirebaseDatabase using Flutter / Dart?

Two problems:

  1. To order/filter on a specific property of each child node, you need to use orderByChild(...) and not just child(...). Right now your code reads /users/email, which doesn't exist.

  2. When you execute a query against the Firebase Database, there will potentially be multiple results. So the snapshot contains a list of those results. Even if there is only a single result, the snapshot will contain a list of one result.

    Your code doesn't handle the list, but prints the key of the location against which the query was executed: users.

So to fix both would look something like this:

DatabaseReference keyRef = FirebaseDatabase.instance.reference();
await keyRef.child('users')
.orderByChild('email')
.equalTo(userList[0].email)
.onChildAdded.listen((Event event) {
print('${event.snapshot.key}');
}, onError: (Object o) {
final DatabaseError error = o;
print('Error: ${error.code} ${error.message}');
});
});

You can also use .once().then(...) but will then have convert dataSnapshot.value to a map, and show the key(s) from that map. Not check, but it should be something like this:

DatabaseReference keyRef = FirebaseDatabase.instance.reference();
await keyRef.child('users')
.orderByChild('email')
.equalTo(userList[0].email)
.once()
.then((DataSnapshot dataSnapshot) {
String newKey = dataSnapshot.value.keys[0];
print(newKey);
});

How do I get the values of each key in Firebase Realtime Database?

If you need both the keys and the values of the stories, one way to do that is to pass two parameters to your callWhenFinished callback:

  getListOfStories(location, callWhenFinished) {
let ref = firebase.database().ref(location)
ref
.once("value")
.then((snapshot) => {
let listOfStoryKeys = [],
listOfStoryValues = [];
snapshot.forEach(function(childSnapshot) {
listOfStoryKeys.push(childSnapshot.key);
listOfStoryValues.push(childSnapshot.val());
})
callWhenFinished(listOfStoryKeys, listOfStoryValues);
})
.catch((error) => {
console.log("Couldn't get list of objects: " + error);
callWhenFinished([], [])
});
}

You can also put the keys and values in a single array, giving the key a name that you're not using for any of your other properties (like $key). That'd look something like:

  getListOfStories(location, callWhenFinished) {
let ref = firebase.database().ref(location)
ref
.once("value")
.then((snapshot) => {
let listOfStories = [];
snapshot.forEach(function(childSnapshot) {
let story = childSnapshot.val();
story["$id"] = childSnapshot.key;
listOfStories.push(story);
})
callWhenFinished(listOfStories);
})
.catch((error) => {
console.log("Couldn't get list of objects: " + error);
callWhenFinished([])
});
}

No matter which option you use, you can then iterate over the story values/keys in the callback implementation, and access both the key and the property values.

How can I get a key from the value in Firebase?

The following should work, based on the documentation

searched_bus = db.child("asanbus").order_by_child("busStopName").equal_to("XYZ").get()
for bus in searched_bus.each():
print(bus.key())

Assumption: there is only one record corresponding to busStopname = "XYZ". If not the case, you may do:

searched_bus = db.child("asanbus").order_by_child("busStopName").equal_to("XYZ").limit_to_first(1).get()

How to get firebase key value

To get the key inside the for..in loop, you can do the following:

  let key = child.key as String
print(key)

Check here for more info:

https://firebase.google.com/docs/database/ios/read-and-write

How to get the key value of a specific child in the Firebase Realtime database (Android Development)?

You're looking to use a query that orders/filters on your subject_name field. Something like this should do the trick:

addedSubjectReference
.orderByChild("subject_name") // First order on a property
.equalTo("java") // Then filter on a value
.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) {
//if (snapshot.exists()) { // This is not needed inside `onChildAdded`
subjectNamesList.add(snapshot.child("subject_name").getValue(String.class));
subjectUuidList.add(snapshot.child("subject_uuid").getValue(String.class));
//}
}


Related Topics



Leave a reply



Submit