【问题标题】:Updating Data within a unique randomly generated ID/KEY in firebase using HTML使用 HTML 在 Firebase 中随机生成的唯一 ID/KEY 中更新数据
【发布时间】:2019-02-03 08:27:00
【问题描述】:
function updateFirebase(){
const fb=firebase.database().ref()
//get field values
author = document.getElementById('uname').value
user_email = document.getElementById('umail').value
data = {author, user_email}
//update database
fb.child('Article/').update(data);
}
</script>
我的代码有问题。我想更新名为“Article”的表中的数据。文章生成了具有唯一键/ID 的项目,每个键都有自己的内容。假设我希望能够编辑“作者”或更改“标题”,问题是他们每个人都有一个我无法访问的随机生成的密钥/ID。例如“-LS39kReBHrKGqNj7h_”。我只能将数据保存在“文章”树中,但不能更改“作者”或“标题”。如何解决此问题以便更改这些属性?
Here is how my firebase looks like
【问题讨论】:
标签:
html
firebase
firebase-realtime-database
【解决方案1】:
这取决于您在更新之前是否在前端有记录引用(在尝试更新之前是否已获取它)。
但一般来说,你有两种选择
- 您可以将键引用存储为对象上的“id”字段。
为此,您首先需要在创建记录时执行两个步骤
// Creates a new record in DB and returns it to you. Now you can get the "key"
const newRecord = firebase.database().ref('TABLE_NAME_REF').push();
newRecord.set({
id: newRecord.key
...
});
如果您在前端获取记录列表,然后想要更新其中一条记录,那就太好了。然后你可以像这样构建参考路径
fb.child('Article/' + record.id ).update(data); // where record is the prefetched thing
- 您需要先根据其字段找到该元素。拥有它后,您可以立即对其进行更新。
为此,您可以简单地执行以下操作:
firebase.database()
.ref('TABLE_NAME_REF') // let's say 'Article'
.orderByChild('RECORD_KEY') // Let's say 'author'
.equalTo('KEY_VALUE') // let's say 'zoranm'
.limitToFirst(1)
.once("value")
.then(res => {
// You need to loop, it always returns an array
res.forEach(record => {
console.log(record.key); // Here you get access to the "key"
fb.child('Article/' + record.key ).update(data); // This is your code pasted here
})
})