Firestore请求,检查文档是否存在



我现在在这个Firestore检查中挣扎了一段时间。

let currentUser = firebase.auth().currentUser;
console.log(currentUser.uid);
let docRef = db.collection("StartNumbers").where('UserId', '==', currentUser.uid);
docRef.get().then((querySnapshot) => {
querySnapshot.forEach((doc) => {
if (doc.exists){
console.log('document exists')
chooseMode.style.display = 'grid';
onlinePopout.style.display = 'none';
console.log('user is logged in');   
} else { 
console.log('no such document');
nameOuter.style.display = 'grid';
}
});    
}).catch ((err) => {
console.log("Error getting document:", err)
})   

如果doc存在,一切正常。如果没有这样的文档,什么也不会发生,没有错误消息,没有console.log…

你能帮我找出我的错误吗?

Queries将返回完全匹配条件的文档,这实际上意味着queryssnapshot中返回的所有文档都存在。因此,在forEach循环中添加if (doc.exists)检查是多余的。

如果没有这样的文档,什么也不会发生。

您应该在QuerySnapshot上使用.empty属性来检查您的查询是否返回任何匹配的文档,如以下所示:

let docRef = db.collection("StartNumbers").where('UserId', '==', currentUser.uid);
docRef.get().then((querySnapshot) => {
if (querySnapshot.empty) {
console.log("NO documents matched the condition")
} else {
console.log(querySnapshot.docs.map(doc => doc.data()))
// proceed with adding HTML elements here
}
})

最新更新