Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if Cloud Firestore query returns something

Let's say my Cloud Firestore looks like this:

users
  ├────random_id_1───{name, email, ...}
  ├────random_id_2───{name, email, ...}
 ...
  └────random_id_n───{name, email, ...}

I created a CollectionReference:

var collectionReference = db.collection("users");

Then I created a Query:

var query = collectionReference.where("name", "==", "John");

My goals is to check if the query finds something or not, I just want this answer (so I can use it in an if-else statement).

If possible, I don't want to use this approach, even that it works:

query.get().then(function(querySnapshot) {
    if (querySnapshot.empty) {
        console.log('no documents found');
    } else {
        // do something with the data
    }
});

It's too much code to give a simple boolean about the query.

like image 712
Daniel Avatar asked Feb 05 '19 19:02

Daniel


People also ask

How do I get specific data from firestore?

Reading data from Firestore There are two ways for retrieving data, which is stored in Cloud Firestore. Calling a method to get the data. Setting a listener for receiving data changes events. We send an initial snapshot of the data, and then another snapshot is sent when the document changes.

What is onSnapshot in firebase?

You can listen to a document with the onSnapshot() method. An initial call using the callback you provide creates a document snapshot immediately with the current contents of the single document. Then, each time the contents change, another call updates the document snapshot.

How do I find my collection reference on firestore?

CollectionReference collectionReference = FirebaseFirestore. getInstance(). collection("public_messages"); ArrayList<String> ids = new ArrayList<>(); //Contains your keys ArrayList<Task<QuerySnapshot>> tasks = new ArrayList<>(); for (String id : ids) { Task<QuerySnapshot> task = collectionReference.


1 Answers

What you've shared is the idiomatic approach to check for the existence of a document, so there aren't any better options.

The only thing I can think of is if you're on an environment that supports async/await in which case you can do this:

let querySnapshot = await query.get();
if (querySnapshot.empty) {
    console.log('no documents found');
} else {
    // do something with the data
}

You could probably even condense the first two lines into:

if ((await query.get()).empty) {
  ...

I don't like this last chance all that much though. Hiding complexity like this always ends up being a leaky abstraction at some point.

like image 178
Frank van Puffelen Avatar answered Oct 19 '22 00:10

Frank van Puffelen