首页 > 解决方案 > 在使用 cloud firestore .get() doc.exists 时,即使文档存在,它也始终保持未定义

问题描述

这是代码:集合名称是“用户名”,文档有一个称为“用户名”的字段,我将检索到的数据限制为 1。我只有一个与查询匹配的文档,并使用控制台日志验证数据是被检索但仍然每次 snapshot.exists 给我一个未定义的

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 也始终未定义

标签: javascriptreactjsfirebasegoogle-cloud-firestore

解决方案


在您的代码中,snapshot是一个QuerySnapshot对象,它是由查询产生的 0 个或多个 DocumentSnapshot 对象的容器。链接的 API 文档表明 QuerySnapshot 上没有“存在”属性。只有DocumentSnapshot具有exists属性,但这不是您在此处拥有的。

即使您期望查询中只有一个文档,您仍然应该检查 QuerySnapshot 以确保它包含您要查找的一个文档。您可以通过检查结果的size()来做到这一点:

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

推荐阅读