简体   繁体   中英

How to check whether data exist in firebase or not in JavaScript?

I am trying to check weather the data exist or not in firebase.

Suppose I want to check weather vivank exist or not Firebase数据库屏幕截图

I used this . But it's not running and not showing any output.

const firebaseRef = firebase.database().ref();

function check() {
  theDataToAdd = 'vivank'
  firebaseRef.once('value', function(snapshot) {
    if (snapshot.hasChild(theDataToAdd)) {
      alert('exists');
    }
  });
}

You can use a code like this to check if such data exists in your firebase database or not:

Ref.once('value', function(snapshot) {
  if (snapshot.hasChild(theDataToAdd)) {
    alert('exists');
  }
});

But this is a bit inefficient as it would first download all data under Ref and then do the check. A bit more efficient solution will be:

Ref.child(theDataToAdd).once('value', function(snapshot) {
  if (snapshot.exists()) {
    alert('exists');
  }
});

This is efficient due to the fact that it's a bit more targeted towards the referenced node.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM