gpt4 book ai didi

javascript - 在 Firebase for Web 应用程序中检索值 - JavaScript

转载 作者:行者123 更新时间:2023-12-03 02:03:09 24 4
gpt4 key购买 nike

我目前正在为大学项目制作 Web 应用程序,需要一些帮助来检索 Firebase 数据库中的值。结构如下:

enter image description here

我想做的是查看特定的 uid 是否存在于引用“地址”的任何地方

这是我的代码:

var refAdd = firebase.database().ref().child('addresses');
refAdd.orderByChild("uid").equalTo(user.uid).once("value", function(snapshot){
console.log("(snapshot) request found for " + snapshot.key);
snapshot.forEach(function(child) {
console.log("request found for " + child.key);
});
});

所以我在这里想做的是查看当前用户 UID 是否存在于“地址”下,如果存在则记录其所在位置的推送键值。

有人知道如何去做吗?

最佳答案

最好的方法可能是对数据进行非规范化。这意味着每次您在特定“地址”项下为特定用户编写“请求”时,您还应该在另一个数据库节点中在用户的 uid 下编写“地址”的“推送”id。

换句话说,根据您的示例,您应该拥有一个如下数据库:

- addresses
+ -LAPf7dNDU...
+ requests
- ......
- addressesByUid
- 9nras7IY..... //You use the user uid as the key of this node
- adressId: "-LAPf7dNDU..." //The key of the address

这样你的查询就会容易得多。

唯一的“困难”是您必须保持两个节点同步。但这可以通过例如轻松完成一组写入,如以下示例(来自文档):

  // Get a key for a new Post.
var newPostKey = firebase.database().ref().child('posts').push().key;

// Write the new post's data simultaneously in the posts list and the user's post list.
var updates = {};
updates['/posts/' + newPostKey] = postData;
updates['/user-posts/' + uid + '/' + newPostKey] = postData;

return firebase.database().ref().update(updates);

最后,请注意,如果有必要,您可以通过执行类似的操作在一个用户 uid 下拥有多个 addressID

- addressesByUid
+ 9nras7IY..... //You use the user uid as the key of this node
- -LAPf7dNDU...: "true"
- -LUTTE66hf...: "true"

关于javascript - 在 Firebase for Web 应用程序中检索值 - JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49928147/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com