Reputation: 107
I just started to use firebase and I am new to the node.js environment im trying to send to get data from my database i got this using this code
var country = sessionStorage.countryname;
var ref = firebase.database().ref('posts/country/' + country + '/')
ref.on('value', function(snapshot) {
snapshot.forEach(function(keysSnapshot) {
var keys = keysSnapshot.val();
console.log('keys', keys);
})
});
I got all the data in keys but i dont know how to access it for example i want to get the age and first_name of each post ..this is what i get in console log
this is the json code
{
"country" : {
"Algeria" : {
"844kh2QXDHgw7i4KBvULpCSO5KE2" : {
"-L9MvZxV2bVjcuKGZx-2" : {
"age" : "26",
"first_name" : "jack",
"gender" : "female",
"home_adress" : "2222222222222222222222222222",
"last_name" : "anonyo",
},
"-L9Mvpnyx1f9DDDygJcG" : {
"age" : "29",
"first_name" : "jazmine",
"gender" : "female",
"home_adress" : "2222222222222222222222222222",
"last_name" : "anony",
}
},
"QgWbVLqInga3JRNuzzlZBCzwkws2" : {
"-L9ES58GkQcZGywqpIWY" : {
"age" : "29",
"first_name" : "jazmine",
"gender" : "female",
"home_adress" : "2222222222222222222222222222",
"last_name" : "anony",
}
}
},
"england" : {
"jdL079kwJUQSBzKE7aNIPInPEHX2" : {
"-L925-sxlxsF5k9LZFHp" : {
"age" : "29",
"first_name" : "jessica",
"gender" : "female",
"home_adress" : "2222222222222222222222222222",
"last_name" : "anony",
}
}
}
}
}
Upvotes: 1
Views: 6571
Reputation: 2340
If you want to iterate all your users:
var objectKeys = Object.keys(keys);
for(x=0; x < objectKeys.length; x++){
var currentKey = objectKeys[x];
var userData = keys.currentKey; //Here you have all the data
console.log(userData);
//Now access the first_name property
var firstName = userData.first_name;
}
I have no test it but it should work.
Upvotes: 0
Reputation: 107
ok this is how i got it working var country = sessionStorage.countryname;
database.ref('posts/country/'+country).once('value').then(function(snapshot) {
var country = snapshot.key ;
snapshot.forEach(function(snapshot1) {
console.log(snapshot1.key); //
snapshot.forEach(function(snapshot2) {
console.log(snapshot2.key); //
snapshot2.forEach(function(snapshot3) {
console.log(snapshot3.key);
console.log(snapshot3.val().first_name)
});
});
});
});
thanks to frank answer here How to retrieve nested child value in Firebase database using javaScript? ty for the help guys
Upvotes: 4
Reputation: 18585
Get it with snapshot.val()[844kh2QXDHgw7i4KBvULpCSO5KE2][-L9MvZxV2bVjcuKGZx-2][age]
. See documentation Read and Write Data on the Web
var starCountRef = firebase.database().ref('posts/' + postId + '/starCount'); starCountRef.on('value', function(snapshot) { updateStarCount(postElement, snapshot.val()); });
Upvotes: 0