0

I have set up a little web front end to insert data into a realtime database. And it is working, below is the relevant code.

Now I would like to improve this code to prevent the user from adding an element with the same url. What is the best way to handle this. I have tried a few things but that did not work. And I do not really want to use the url as the key either.

Please let me know for any good suggestion.

<form id='adTF'>
  Name: <input id='name' type='text' maxlength=128 size=50 value='' required>
  <br/><br/>
  URL: <input id='url' type='text' maxlength=128 size=50 value='' required>
  <br/><br/>
  <input type='submit' value='Submit'>
</form>

<script>
  document.getElementById('adTF').addEventListener('submit',addNewItem)

  var dbReference = firebase.database().ref('ItemList');

  function addNewItem(event) {
    event.preventDefault();

    const url = document.getElementById('url').value.trim(),
          name = document.getElementById('name').value.trim();

    let newItem = dbReference.push();
    newItem.set({url:url,name:name});
    document.getElementById('url').value = '';
    document.getElementById('name').value = '';
  } /* End of addNewItem */
</script>
Michel
  • 10,303
  • 17
  • 82
  • 179

1 Answers1

1

If you have the following structure:

ItemList
    randomId
         url : url
         name:name

Then you can do the following:

  var dbReference = firebase.database().ref('ItemList');
  dbReference.orderByChild("url").equalTo(url).on("value", function(snapshot) {
      if (snapshot.exists()) {

           }
       });

This will check if the url exists in the database or not, if it doesn't exist you can then add it.

Peter Haddad
  • 78,874
  • 25
  • 140
  • 134