简体   繁体   中英

Test if a data exist in Firebase

I would like test if a data exist in Firebase before to add it. But I have a problem with my method: I try to list all data with this Javascript code:

var theDataToAdd = userName;
var usersRef = new Firebase('https://SampleChat.firebaseIO-demo.com/users/');
usersRef.on('child_added', function(snapshot) {
   var message = snapshot.val();
   if (message.name == theDataToAdd)
      alert ("exist");
});

But if the user doesn't exist, it will be added before, then my code says that he exists. You will say that is normal because my alert is called only when "child_added", but I don't see how do.

I have also try with the "value" event but my "message.name" is empty.

How can I fix it?

You can use DataSnapshot.hasChild to determine if a certain child exists.

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

Here's a quick jsfiddle showing how this works: http://jsfiddle.net/PZ567/

But this will download all data under usersRef and perform the check on the client. It's much more efficient to only download the data for the user you want to check, by loading a more targeted ref:

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

I use the following code:

var theDataToAdd = userName;
var ref = new Firebase('https://SampleChat.firebaseIO-demo.com/users/' + theDataToAdd);
ref.on('value', function(snapshot) {
   if (snapshot.exists())
      alert ("exist");
   else
      alert ("not exist");
});

My method is more lightweight than this:

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

because a client will not fetch all users data, which can be huge.

Way to check if data exists or not in a Firebase Db for ANDROID.

 final Firebase firebaseRef = new Firebase(<Your_Firebase_URL>/Users).child(username);


firebaseRef.addListenerForSingleValueEvent(new ValueEventListener) {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
    if (dataSnapshot.exists()) {
        // User Exists
    }
}

@Override
public void onCancelled(FirebaseError firebaseError) {

}
});

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