简体   繁体   中英

While using cloud firestore .get() doc.exists always remains undefined eventhough the document exists

this is the code: the collection name is"usernames" and documents have a field known as "userName" and i am limitting the data retrieved to 1. i have exactly one document that matches the query and using console logs i verified that data is being retrieved but still everytime snapshot.exists gives me an undefined

db.collection("usernames").where("userName", "==", userName.toString()).limit(1).get()
    .then(snapshot => {
        if(snapshot.exists)
            window.alert("Username already exists");
        else{
            window.alert("Username added");
            db.collection("usernames").add({
                profilePic: "",
                userName: userName
        
            })
        
            db.collection("users").add({
                age: age,
                email: email,
                firstName: fname,
                lastName: lname,
                mobileNo: mobileNo,
                password: password,
                userName: userName
        
            })
            .then( user => dispatch(addNewUser(user)))
            .catch(error => dispatch(addUserFailed(error)));
        }
    })
    .catch(error => dispatch(addUserFailed(error)));

snapshot.exists always is undefined even though the documents are read

In your code, snapshot is a QuerySnapshot object, which is a container for 0 or more DocumentSnapshot objects resulting from the query. The linked API documentation suggests that there is no attribute "exists" on a QuerySnapshot. Only DocumentSnapshot has an exists property, but that's not what you have here.

Even if you are expecting exactly one document from the query, you still should check the QuerySnapshot to make sure it contains the one document you're looking for. You could do this by checking the size() of the results:

.then(querySnapshot => {
    if (querySnapshot.size() > 0) {
        const docSnapshot = querySnapshot.docs[0];
    }
    else {
        // decide what you want to do if no results
    }

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