Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check if a firebase database value exists?

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

like image 894
James Avatar asked May 24 '16 05:05

James


People also ask

How can I check if a value exists already in a Firebase data class Android?

child(busNum). exists() tests for the existence of a value at location BusNumber/<busNum> . It will not be true unless busNum is one of the keys created by push() .

How do I check my database in Firebase?

To see your current Realtime Database connections and data usage, check the Usage tab in the Firebase console. You can check usage over the current billing period, the last 30 days, or the last 24 hours.

Can we retrieve data from Firebase?

Firebase data is retrieved by either a one time call to GetValueAsync() or attaching to an event on a FirebaseDatabase reference. The event listener is called once for the initial state of the data and again anytime the data changes.

What is DataSnapshot in Firebase?

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


2 Answers

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")         }       }) 
like image 91
ismael33 Avatar answered Sep 20 '22 19:09

ismael33


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")     } })  
like image 41
Frank van Puffelen Avatar answered Sep 21 '22 19:09

Frank van Puffelen