37

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?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Max
  • 373
  • 1
  • 3
  • 4

3 Answers3

60

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');
  }
});
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • 1
    Thanks, it works! However, now, I have another problem: Firebase.DataSnapshot.hasChild failed: First argument was an invalid path: "jean.paul". Paths must be non-empty strings and can't contain ".", "#", "$", "[", or "]" So, in this case, is it possible to put a "." in the path with a cast, another method or no? – Max Jul 18 '14 at 14:08
  • The error message explicitly says that you can't have a `.` in the name/path. Easiest is to simply disallow such characters from your names to. If you can't disallow them, you should encode them (e.g. `.` to `%20`) or simply remove them from the name you send to Firebase. – Frank van Puffelen Jul 18 '14 at 14:20
  • OK Max. If you have problems with the mapping, just open a new question for it. We've recently seen a few people running into the limitations on name/path characters, so could do with a good question on the topic. – Frank van Puffelen Jul 18 '14 at 15:41
  • Is it possible to store data if they don't exist in one firebase call? – Qwerty Sep 07 '15 at 13:11
  • This solution is slow. Please see my post below. – Dmytro Sep 04 '17 at 07:54
  • @FrankvanPuffelen Same we can do with if (snapshot.exists(theDatatoAdd)). What is difference between hasChild and exists? Which one is better? – Zohra Khan Mar 02 '18 at 05:27
  • `exists()` takes no arguments. You call it on a snapshot, to see if data exists in that snapshot. So `snapshot.hasChild(theDataToAdd)` it equivalent to `snapshot.child(theDataToAdd).exists()`. – Frank van Puffelen Mar 02 '18 at 14:00
20

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.

Dmytro
  • 1,290
  • 17
  • 21
  • 1
    Please notice, the client still fetches the data that is UNDER the provided url 'https://SampleChat.firebaseIO-demo.com/users/' + theDataToAdd and returns it as part of the DataSnapshot. I havn't found a way to check the existnace without fetching the datasnapshot of the url – user2924714 Oct 27 '16 at 14:01
  • 1
    Yes, but it just fetches data only for one user, not all users as proposed by Frank van Puffelen. I also don't know solution without fetching at all. – Dmytro Dec 04 '16 at 11:31
  • in the first snippet of code downloads all users data to check if it exist even though you're specifying a reference to the node on var ref = new Firebase('https://SampleChat.firebaseIO-demo.com/users/' + theDataToAdd); ? – SergioGeeK7 Jan 22 '18 at 22:06
  • @SergioGeeK7 No – Dmytro Apr 26 '18 at 07:45
11

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) {

}
});