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
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")
}
})
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.
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);
}];
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) {
}
});