40

I'm using the Realtime Database with Google's Firebase, and I'm trying to check if a child exists.

My database is structured as the following

- / (root)
-   /users/
–-    /james/
--    /jake/
-   /rooms/
--    /room1/
---      (room 1 properties)
--    /room2/
---      (room 2 properties)

I would like to check if room1 exists. I have tried the following:

let roomName:String = "room1"
roomsDB.child(roomName).observeSingleEventOfType(.Value) { 
(snap:FIRDataSnapshot) in
    let roomExists:Bool = snap.value != nil ? "TAKEN" : "NOT TAKEN"
 }

In accessing snap.value it returns a JSON of the properties of that room, but how would I check if the room (/rooms/room1/) is there to begin with?

Comment if any clarification is needed

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
James
  • 787
  • 1
  • 7
  • 15

6 Answers6

84
self.ref = FIRDatabase.database().reference()

   ref.child("rooms").observeSingleEvent(of: .value, with: { (snapshot) in

        if snapshot.hasChild("room1"){

            print("true rooms exist")

        }else{

            print("false room doesn't exist")
        }


    })
ismael33
  • 1,069
  • 8
  • 5
  • this code is for the Firbase 3 (last one ... may 2016) – ismael33 May 24 '16 at 06:38
  • you can check also if there is any room with haschildren() if it is false , it has no room at all ... – ismael33 May 24 '16 at 06:40
  • 2
    What if the parrent of the object you'd like to check for has a lot of data inside? Will it all be downloaded? – rhcpfan May 07 '17 at 20:36
  • What about for Firebase 4.0 that was just released May 17 2017!? – Famic Tech May 19 '17 at 19:45
  • @rhcpfan I think yes, that's why we need to use the query functions of Firebase. – Glenn Posadas Sep 08 '17 at 06:23
  • 1
    While this answer works, it downloads more data than needed. Use `ref.child("rooms/room1").observeSingleEvent(of: .value, with: { (snapshot) in if snapshot.exists(){` to reduce the amount of data read from the database. Also see my alternate answer: https://stackoverflow.com/a/50494190 – Frank van Puffelen Nov 09 '18 at 03:34
30

While the answer of @ismael33 works, it downloads all the rooms to check if room1 exists.

The following code accomplishes the same, but then only downloads rooms/room1 to do so:

ref = FIRDatabase.database().reference()

ref.child("rooms/room1").observeSingleEvent(of: .value, with: { (snapshot) in
    if snapshot.exists(){
        print("true rooms exist")
    }else{
        print("false room doesn't exist")
    }
}) 
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • This way is MUCH better. As well as not having to download all the data, if you have restriction in rules like me where you can't read the equivalent of the `room` object, you can go further along the tree without causing issues to check if it does exist. – George Aug 26 '18 at 09:48
8

I have some suggestions by using firebase.You check it from firebase.

We can test for the existence of certain keys within a DataSnapshot using its exists() method:

A DataSnapshot contains data from a Firebase database location. Any time you read data from a Firebase database, you receive the data as a DataSnapshot.

A DataSnapshot is passed to the event callbacks you attach with on() or once(). You can extract the contents of the snapshot as a JavaScript object by calling its val() method. Alternatively, you can traverse into the snapshot by calling child() to return child snapshots (which you could then call val() on).

A DataSnapshot is an efficiently-generated, immutable copy of the data at a database location. They cannot be modified and will never change. To modify data, you always use a Firebase reference directly.

exists() - Returns true if this DataSnapshot contains any data. It is slightly more efficient than using snapshot.val() !== null.

Example from firebase documentation(javascript example)

var ref = new Firebase("https://docs-examples.firebaseio.com/samplechat/users/fred");
ref.once("value", function(snapshot) {
  var a = snapshot.exists();
  // a === true

  var b = snapshot.child("rooms").exists();
  // b === true

  var c = snapshot.child("rooms/room1").exists();
  // c === true

  var d = snapshot.child("rooms/room0").exists();
  // d === false (because there is no "rooms/room0" child in the data snapshot)
}); 

Also please refer this page(already mentioned in my comment)

Here there is an example using java.

Firebase userRef= new Firebase(USERS_LOCATION);
userRef.child(userId).addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot snapshot) {
        if (snapshot.getValue() !== null) {
            //user exists, do something
        } else {
            //user does not exist, do something else
        }
    }
    @Override
    public void onCancelled(FirebaseError arg0) {
    }
});

I hope you got an idea now.

Renjith V R
  • 2,981
  • 2
  • 22
  • 32
  • I understand what you're saying, but I was looking for Firebase 3. I should have specified. Thanks for the answer. – James May 24 '16 at 08:45
1

You can check snapshot.exists value.

NSString *roomId = @"room1";
FIRDatabaseReference *refUniqRoom = [[[[FIRDatabase database] reference]
                                      child:@"rooms"]
                                     child:roomId];

[refUniqRoom observeSingleEventOfType:FIRDataEventTypeValue
                            withBlock:^(FIRDataSnapshot * _Nonnull snapshot) {

    bool isExists = snapshot.exists;
    NSLog(@"%d", isExists);
}];
Muhammed Tanriverdi
  • 3,230
  • 1
  • 23
  • 24
0

Use any of them So simple and easy ... Which way you like

ValueEventListener responseListener = new ValueEventListener() {
    @Override    
    public void onDataChange(DataSnapshot dataSnapshot) {
        if (dataSnapshot.exists()) {
            // Do stuff        
        } else {
            // Do stuff        
        }
    }

    @Override    
    public void onCancelled(DatabaseError databaseError) {

    }
};

FirebaseUtil.getResponsesRef().child(postKey).addValueEventListener(responseListener);

function go() {
  var userId = prompt('Username?', 'Guest');
  checkIfUserExists(userId);
}

var USERS_LOCATION = 'https://SampleChat.firebaseIO-demo.com/users';

function userExistsCallback(userId, exists) {
  if (exists) {
    alert('user ' + userId + ' exists!');
  } else {
    alert('user ' + userId + ' does not exist!');
  }
}

// Tests to see if /users/<userId> has any data. 
function checkIfUserExists(userId) {
  var usersRef = new Firebase(USERS_LOCATION);
  usersRef.child(userId).once('value', function(snapshot) {
    var exists = (snapshot.val() !== null);
    userExistsCallback(userId, exists);
  });
}

Firebase userRef= new Firebase(USERS_LOCATION);
userRef.child(userId).addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot snapshot) {
        if (snapshot.getValue() !== null) {
            //user exists, do something
        } else {
            //user does not exist, do something else
        }
    }
    @Override
    public void onCancelled(FirebaseError arg0) {
    }
});
Sohaib Aslam
  • 1,245
  • 17
  • 27
0
users = new HashMap<>();
                users.put("UserID", milisec);
                users.put("UserName", username);
                users.put("UserEmailID", email);
                users.put("UserPhoneNumber", phoneno);
                users.put("UserPassword", hiddenEditPassword);
                users.put("UserDateTime", new Timestamp(new Date()));
                users.put("UserProfileImage", " ");

                FirebaseFirestore.getInstance().collection("Users").document(phoneno).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
                    @Override
                    public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                        if (task.getResult().exists()) {
                            Toast.makeText(SignupActivity.this, "Already User", Toast.LENGTH_SHORT).show();

                        } else {
                            FirebaseFirestore.getInstance().collection("Users")
                                    .document(phoneno).set(users).addOnCompleteListener(new OnCompleteListener<Void>() {
                                @Override
                                public void onComplete(@NonNull Task<Void> task) {
                                    Toast.makeText(SignupActivity.this, "Registers", Toast.LENGTH_SHORT).show();

                                }
                            });
                        }
                        hideProgressDialog();
                    }
                });`
enter code here