我需要从用户节点查询用户的信息,然后将其显示在我的html表中,目前我只能将Firebase数据库中请求节点的状态子级查询到我的html表中。
如何查询每个用户uid所在节点的信息? 这是我的结构,到目前为止我可以显示待处理状态。由于用户只有 1 个 uid,因此我认为可以在每个用户的待处理状态旁边显示其名称。
] 1
这是我查询待处理的方式,
var database = firebase.database().ref().child('Request').child('Pending');
database.once('value', function(snapshot){
snapshot.forEach(function(data){
var ReqStatus = data.val().request_status;
content +='<tr>'
content +='<td>' + ReqStatus+ '</td>';
content +='</tr>';
});
$('#mytable').append(content);
}
);
最佳答案
要为每个请求加载用户数据,您需要使用额外的监听器。最简单的方法是这样的:
var root = firebase.database().ref();
var database = root.child('Request').child('Pending');
database.once('value', function(snapshot){
snapshot.forEach(function(data){
var reqStatus = data.val().request_status;
var uid = data.key;
root.child('User').child(uid).once('value', function(userSnapshot) {
var username = userSnapshot.val().username;
content += '<tr>'
content += '<td>' + username+ '</td><td>' + reqStatus+ '</td>';
content += '</tr>';
})
});
$('#mytable').append(content);
});
关于此方法的一些注意事项:
- 您对 Firebase 执行了更多调用,但自 Firebase pipelines those requests 起,性能通常会相当不错。 .
- 如果用户有多个请求,您将多次加载该用户的节点。如果这是您的应用的真实用例,您可能希望保留最近加载的用户的缓存。
- 此代码加载整个用户节点。如果您只需要他们的名字,您可以监听
username
子节点以减少带宽使用:root.child('User').child(uid).child('username' ).once('值'...
. 正如 André 评论的那样:您可能希望将作者的用户名存储在每个请求节点中,以减少读取次数并使代码更简单。在 JavaScript 中做到这一点相当简单:
var root = firebase.database().ref(); var database = root.child('Request').child('Pending'); database.once('value', function(snapshot){ snapshot.forEach(function(data){ root.child('User').child(data.key).child('username').once('value', function(userSnapshot) { data.ref.update({ username: userSnapshot.val() }); }) }); });
关于javascript - 如何在 Javascript 中使用 userID 查询 Firebase 中的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53481647/