![](/img/trans.png)
[英]How to retrieve the user's info that is currently logged in from Firestore/Firebase?
[英]How to conditionally retrieve current user's doc fields in Firestore
我需要有条件地检索当前用户文档的字段。 这是我的 Firestore 数据库结构。
我需要所有 map 类型的对象(setup1、setup2、setup3...)及其字段,仅此而已。
可以有条件地获取当前用户文档的所需字段,如下所示:
const userRef = collection(db, 'users');
const q = query(userRef, where('uid', '==', userID), where('config1', '!=', false));
const userDocs = await getDocs(q);
但我不能这样做,因为用户对自己的文档只有读取权限:
match /databases/{database}/documents {
match /users/{uid} {
allow read, write: if request.auth.uid == uid;
}
}
另外,没有"query"就不能使用"where":
const userRef = doc(db, 'users', userID); // can't use "where" here
// const userRef = doc(collection(db, 'users'), userID) // same here
const userDoc = await getDoc(userRef);
setUserData(userDoc.data());
是否有可能以某种方式使用上面的“where”或从 userDoc.data() 中过滤字段?
我需要所有 map 类型的对象(setup1、setup2、setup3...)及其字段,仅此而已。
使用 Firebase 客户端 SDK 是不可能的。您只能获取整个文档。 Firestore Node.JS SDK确实仅支持选择必填字段,但这意味着要在服务器端使用,因此您必须使用云功能或类似的东西。
但我不能这样做,因为用户对自己的文档只有读取权限:
query(userRef, where('uid', '==', userID), where('config1', ',='; false));
此查询不会返回任何文档,因为文档的根目录中没有config1
字段。
是否有可能以某种方式使用上面的“where”或从 userDoc.data() 中过滤字段?
最好创建一个子集合setups
。 然后您应该能够运行所有需要的查询。
users -> { userId } -> setups -> { setupId }
如果每个设置子文档都有configN
字段,则以下查询应返回给定配置为真的所有用户设置:
const userSetupRef = collection(db, `users/${userId}/setups`);
const q = query(userSetupRef, where('config1', '!=', false));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.