Lancer EX
Lancer EX

Reputation: 37

Updating Data within a unique randomly generated ID/KEY in firebase using HTML

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>

I have problem with my code. I want to update the data inside a table named "Article". Article has generated items with a unique key/id and each key has its own content. Lets say I want to be able to edit the "author" or change the "title", the problem is they each have a randomly generated key/id that I cant access. for example that "-LS39kReBHrKGqNj7h_". I can only save the data inside the "Article" tree but I cant change the "author" or the "title". How do i get a workaround this so I can change those properties?

Here is how my firebase looks like

Upvotes: 1

Views: 911

Answers (1)

Sam Uherek
Sam Uherek

Reputation: 313

It depends whether you have the record reference on the frontend before update or not (whether you have fetched it before you are trying to update it).

But generally, you have two options

  1. You can store the key reference as an "id" field on the object. To achieve that, you need two step process when creating the record at the first place
// 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
  ...
});

This is great if you fetch the list of records on the frontend and then you want to update one of them. Then you can just build the ref path like this

fb.child('Article/' + record.id ).update(data); // where record is the prefetched thing
  1. You need to find the element based on its fields first. And once you have it, you can update it right away. To achieve this, you can simply do something like:
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
   })
  })

Upvotes: 1

Related Questions