Reputation: 321
I was doing a simple project when I encountered a problem in the firestore database code, When I check if a document exists it only returns true but never false event when it should do
My Code:
db.collection("Users")
.where("email", "==", state.email_value).get()
.then(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
if(doc.exists) {
console.log("Document Exist");
} else {
console.log("Document Doesn't Exist);
}
});
});
The Code only executes when the condition is true but not false. I even tried outputing the doc.exists
value but it only outputs when its true
Upvotes: 0
Views: 2198
Reputation: 598765
If there are no documents, the querySnapshot.forEach(function(doc) ...
will never be entered.
You'll want to instead check if the query itself has results:
db.collection("Users")
.where("email", "==", state.email_value).get()
.then(function(querySnapshot) {
if (!querySnapshot.empty) {
console.log("Document Exist");
}
else {
console.log("Document Doesn't Exist");
}
});
For situations like this, I highly recommend keeping the reference documentation of Firebase handy: https://firebase.google.com/docs/reference/js/firebase.firestore.QuerySnapshot
Upvotes: 3