javascript - 在使用 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 也始终未定义
解决方案
在您的代码中,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
}
推荐阅读
- php - 从一个url下载的json信息是加密的
- javascript - why does it not 'add to cart' when I click add to cart?
- excel - COUNTIF 跨多个“重命名”工作表
- asp.net - 在单页应用程序中添加服务器端代码
- r - Rmarkdown YAML 标头中的作者从属关系,使用 rticles
- ruby-on-rails - 如何将 ajax 附加到 Rails 中的关注/取消关注链接
- android - ListView:如何在单击 ListView 中的按钮时转到新活动?
- c++ - Visual Studio 17 调试属性未导出到模板
- user-interface - 如何在 GUI 中实现我的 while 循环以使用 Visual Studio 在 C/C++ 中保持按键
- python - 是否可以仅使用哈希来查找文件和文件路径