我刚刚开始使用firebase,我是node.js环境的新手 我试图发送从我的数据库中获取数据我得到了这个使用此代码
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);
})
});
我获得了密钥中的所有数据,但我不知道如何访问它,例如我想获得每个帖子的年龄和first_name ..这是我在控制台日志中得到的
这是json代码
{
"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",
}
}
}
}
}
答案 0 :(得分:0)
如果您想迭代所有用户:
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;
}
我没有测试它,但它应该工作。
答案 1 :(得分:0)
使用snapshot.val()[844kh2QXDHgw7i4KBvULpCSO5KE2][-L9MvZxV2bVjcuKGZx-2][age]
获取。请参阅文档Read and Write Data on the Web
var starCountRef = firebase.database().ref('posts/' + postId + '/starCount'); starCountRef.on('value', function(snapshot) { updateStarCount(postElement, snapshot.val()); });
答案 2 :(得分:0)
好的,这就是我如何使用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)
});
});
});
});
感谢这里的坦率回答How to retrieve nested child value in Firebase database using javaScript? ty帮助人们