Firebase Realtime Web Always Returns True to snapshot.exists()

Viewed 175

I am using Firebase Realtime Database to create a simple URL shortener. My goal, right now, is to look at the alias the user picked and check the database to see if it already exists. If the alias exists, the function is returned and the user is asked to create a new alias. If not, the data is added to the DB.

The problem I am running into is that snapshot.exists() always returns true. Even if the alias isn't in the database. I have looked at this question and several other questions, but they are all over two years old and are likely outdated.

My code looks like this:

const dbRef = ref(getDatabase());

function submitData() {
  var linkAlias = document.getElementById("alias").value;
  var linkInput = document.getElementById("text").value;
  var linkAuto = document.getElementById("auto").value;
  console.log(linkAlias)
  get(dbRef, `${linkAlias}`).then(function(snapshot) {
    console.log(linkAlias)
    if (snapshot.exists() == true) {
      console.log(snapshot.val());
      alert("This alias already exists!");
      return;
    } else {
      sendDataToDB(linkAlias, linkInput, linkAuto);
      alert("Success!")
    }
  });
}
1 Answers

In my opinion, after trying to solve this problem for weeks, it may be better to use the Object that my code thinks is the snapshot of just the single alias. Instead, it is a Dict of all the aliases and their URLs.

For example, I can define my Snapshot value:

var codeData = snapshot.val();

And then I can search for the alias in the dictionary keys or values:

if (Object.keys(codeData).includes(linkAlias) === true) {
  ...

I'm going to go with this answer because nothing else has worked for me.

Related