Firebase snapshot.key not returning actual key?
When you run a query at a location, the result will be a list of the matching children. Even if there is only a single matching item, the result will be a list of one child.
You're printing the key of all resulting children. Since there is no single result, the SDK prints the key of the location/collection that you queried: users
.
What you're likely looking for is to loop over the matching children and print their keys:
let query = usersRef.queryOrderedByChild("email").queryEqualToValue(email)
query.observeEventType(.Value, withBlock: { snapshot in
for child in snapshot.children {
print(child.key)
}
})
can't get the key of a datasnapshot
As @FrankVanPuffelen suggested, it seems 'key' is no longer a function, but rather a variable. So
var key = dataSnapshot.key;
does work, but
var key = dataSnapshot.key();
doesn't.
Unable to retrieve keys of firebase data
I got it. Apparently you do not need to put the (). So I changed
var key = childSnapshot.key();
to
var key = childSnapshot.key;
and it worked.
How to pull snapshot key & values into list through Map ?
In this code you only use the element.value
of each node in your results:
return Items.fromRTDB(Map<String, dynamic>.from(element.value));
If you also want to get the key of each item, you will have to also use element.key
in there and pass that to your Items
object.
Something like this:
Items.fromRTDB(element.key, Map<String, dynamic>.from(element.value));
...
class Items{
final String key;
final String item;
final String expiryDate;
final String quantity;
final String user;
Items({required this.key, required this.item, required this.expiryDate, required this.quantity, required this.user});
//Mapping from real-time database
factory Items.fromRTDB(String key, Map<String, dynamic> data) {
return Items(
key: key,
item: data['item'],
expiryDate: data['exp'],
quantity: data['qty'],
user: data['user'],
);
}
}
Firebase data snapshot returns key but no .val()
The issue was that I didn't wait for Firebase to return the userID before running my query:
// this.props.userID is undefined
let userPath = `user/${this.props.userID}/${this.state.topic}`
The solution was to call this.databaseListenerOn()
within onAuthStateChanged
to ensure that it's called once I have the userID.
How to get the key from a Firebase data snapshot?
You could do something like this:
var key = Object.keys(snapshot.val())[0];
Ref: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
The Object.keys() method returns an array of a given object's own
enumerable properties, in the same order as that provided by a
for...in loop (the difference being that a for-in loop enumerates
properties in the prototype chain as well).
dataSnapShot.getKey() not returning the actual push key
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.
So to get the snapshot of the individual child node, you need to loop over the result:
Query reference=FirebaseDatabase.getInstance().getReference().child("products").orderByChild("name").equalTo("iphon");
reference.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
String key=childSnapshot.getKey();
Log.i(TAG,key);
}
}
How to get value from firebase without the snapshot key [JS]
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 Topics
Swiftui: Pop to Root View When Selected Tab Is Tapped Again
How to Use the Appropriate Color Class For the Current Platform
Swift 2 to 3 Migration for Prepareforsegue
Open Uidatepicker Programmatically in iOS 14
Generating Resource_Bundle_Accessor, Type 'Bundle' Has No Member 'Module'
Swift 2.0: Protocol Extensions: Two Protocols with the Same Function Signature Compile Error
Apply a Shadow on a Uiview That Have Same Corner Radius Than View
Transparent Background for Texteditor in Swiftui
Swift: Extending Functionality of Print() Function
Extension May Not Contain Stored Property But Why Is Static Allowed
Pass Variables from One Viewcontroller to Another in Swift
May I Create an Instance of a Structure Using a Simple Int
Add "For In" Support to Iterate Over Swift Custom Classes
What's the How to Use an Objective-C Category Within Swift
Binary Operator '/' Cannot Be Applied to Two 'Double' Operands
Swift Date(Byadding:To:) Returns Nil for Trivial Calculation in Repl