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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With