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 goal 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.
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 goal 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.
Share Improve this question edited Nov 20, 2022 at 14:50 Daniel asked Feb 5, 2019 at 19:35 DanielDaniel 7,7249 gold badges36 silver badges99 bronze badges1 Answer
Reset to default 21What 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.