![](/img/trans.png)
[英]Firestore query returns empty array when there is data that should be returned
[英]How to handle a returned Firestore query when there is not such data?
我正在尝试通过查询“用户”集合的“uid”字段从 Firestore 中提取用户信息。 哪个工作正常。
问题是当没有匹配 uid 的用户时,我希望 function 返回 false 或 null 以便我可以使用此 function 来创建用户配置文件
但即使查询不成功,querySnapshot 也始终返回包含元数据的 object。
那么我该如何处理呢?
async function getUserData (uid) {
const usersRef = collection(db, "users");
const q = query(usersRef, where("uid", "==", uid));
const querySnapshot = await getDocs(q);
console.log(querySnapshot);
return (querySnapshot.forEach((doc) => {
// doc.data() is never undefined for query doc snapshots
if(doc) {
return doc.data();
} else {
console.log('else');
return false;
}
}));
};
QuerySnapshot
有一个empty
属性,当没有文档与查询匹配时为true
。 如果为空,则可以返回false
如下所示:
// Returns array of matched documents' data
return querySnapshot.empty ? false : querySnapshot.docs.map((d) => d.data());
使用用户的 UID 作为文档 ID 可能会更好(如果用户在您的用例中只能有一个),因此您可以按用户 ID 获取单个文档,如下所示:
const userRef = doc(db, "users", uid);
const docSnap = await getDoc(userRef); // not getDocs
return docSnap.data() || false; // .data() if undefined is doc doesn't exist
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.