[英]How to handle a returned Firestore query when there is not such data?
I am trying to pull a user's information from Firestore by querying the 'uid' field of the 'users' collection.我正在尝试通过查询“用户”集合的“uid”字段从 Firestore 中提取用户信息。 Which works fine.
哪个工作正常。
The problem is when there is no user with a matching uid, I would like the function to return false or null so that I can use this function in an if statement to create a user profile问题是当没有匹配 uid 的用户时,我希望 function 返回 false 或 null 以便我可以使用此 function 来创建用户配置文件
but querySnapshot always returns an object containing meta data even if the query is not successful.但即使查询不成功,querySnapshot 也始终返回包含元数据的 object。
So How can I handle this?那么我该如何处理呢?
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;
}
}));
};
The QuerySnapshot
has a property empty
that is true
when no document matched the query. QuerySnapshot
有一个empty
属性,当没有文档与查询匹配时为true
。 You can return false
if it's empty is shown below:如果为空,则可以返回
false
如下所示:
// Returns array of matched documents' data
return querySnapshot.empty ? false : querySnapshot.docs.map((d) => d.data());
It might be better to use user's UID as the document ID (if a user can have only one in your use case) so you can fetch a single document by user ID like this:使用用户的 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.