Georg
Georg

Reputation: 3930

Check if an object with a certain query exists in Firebase

I'd like to check if an object with a certain property set to a value exists.

Here's a sample of what my data on Firebase might look like:

object: {
  object-one: {
    id: "something"
  }
}

And now I want to fetch an object with an id that doesn't exist:

let objectsRef = FIRDatabase.database().reference().child("object")
let query = objectsRef.queryOrderedByChild("id").queryEqualToValue("something else")

query.observeSingleEventOfType(.Value, withBlock: { (snapshot) in
  // Never get's called
})

As there is no entry with id = "something else" the completion will never get called. But how should I know if it's not called because of internet problems or just because that object really doesn't exist?!?

Upvotes: 0

Views: 1134

Answers (2)

Rakesh K
Rakesh K

Reputation: 172

You can use valueEventListner. It fetches the current data and listens for any further updates. In case the data is not present dataSnapshot.exists() will return false.

e.g. My database contains list of user objects, with emailId being one of the fields in each user object.

[
    user1: {emailId: [email protected]},
    user2: {emailId: [email protected]}
]

I can search by emailId field and check if that user is present or not.

ref.orderByChild("emailId").equalTo("[email protected]").addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                System.out.println(dataSnapshot.exists());//false, if values is not present
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

Upvotes: 1

Related Questions