简体   繁体   中英

Can't check if document exists in cloud firestore database and with reactjs

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM