How do I check if a firebase database value exists?
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()
oronce()
. You can extract the contents of the snapshot as a JavaScript object by calling itsval()
method. Alternatively, you can traverse into the snapshot by callingchild()
to return child snapshots (which you could then callval()
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.
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);
}];
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")
}
})
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")
}
})