How do I check if a firebase database value exists?

James picture James · May 24, 2016 · Viewed 57.1k times · Source

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

Answer

ismael33 picture ismael33 · May 24, 2016
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")
        }


    })