一个唯一的随机生成的ID /在火力使用HTML KEY内更新数据

问题描述 投票:0回答:1

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>

我有问题,我的代码。我想更新一个名为“文章”表里面的数据。文章项目产生了一个独特的键/ ID和每个按键都有它自己的内容。比方说,我希望能够编辑的“作者”或更改“标题”,问题是他们每个人都有一个随机产生的密钥/ ID,我不能访问。例如说:“-LS39kReBHrKGqNj7h_”。我只能保存数据的“文章”树内,但我不能改变的“作者”或“标题”。我如何得到一个解决方法这这样我就可以改变这些属性呢?

Here is how my firebase looks like

html firebase firebase-realtime-database
1个回答
1
投票

这取决于你是否对前端的参考记录更新之前与否(是否已获取它,你要更新之前)。

但是总体来说,你有两个选择

  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
  1. 你需要找到基于其领域第一个元素。一旦你拥有了它,你可以更新它的时候了。要做到这一点,你可以简单地这样做:
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
   })
  })
© www.soinside.com 2019 - 2024. All rights reserved.