Javascript 使用cloud firestore.get()时,即使文档存在,doc.exists始终保持未定义状态

Javascript 使用cloud firestore.get()时,即使文档存在,doc.exists始终保持未定义状态,javascript,reactjs,firebase,google-cloud-firestore,Javascript,Reactjs,Firebase,Google Cloud Firestore,代码如下: 集合名称是“usernames”,文档有一个名为“userName”的字段,我将检索的数据限制为1。我正好有一个文档与查询匹配,并且使用控制台日志验证了正在检索数据,但每次snapshot.exists都会给我一个未定义的 db.collection("usernames").where("userName", "==", userName.toString()).limit(1).get() .then(snaps

代码如下: 集合名称是“usernames”,文档有一个名为“userName”的字段,我将检索的数据限制为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始终是未定义的,即使在代码中读取了文档,
snapshot
是一个对象,它是查询产生的0个或多个DocumentSnapshot对象的容器。链接的API文档表明QuerySnapshot上没有“存在”属性。只有一处房产,但那不是你这里的

即使您只希望查询中有一个文档,也应该检查QuerySnapshot以确保它包含您要查找的一个文档。您可以通过检查结果列表来完成此操作:

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

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

即使您只希望查询中有一个文档,也应该检查QuerySnapshot以确保它包含您要查找的一个文档。您可以通过检查结果列表来完成此操作:

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