[英]Firebase Firestore - how to retrieve an array field from a specific document and use those array values to map documents
I have user and group collections. Under the user collection, each document id is a user UID and each user document has an array field "userGroups" which contains the groups that user belongs to and those groups are the group's document ID under group collection.我有用户和组 collections。在用户集合下,每个文档 ID 都是一个用户 UID,每个用户文档都有一个数组字段“userGroups”,其中包含用户所属的组,这些组是组集合下组的文档 ID。
I have been able to retrieve the userGroups array for the current user which i stored in groupRef (see code below).我已经能够检索存储在 groupRef 中的当前用户的 userGroups 数组(请参见下面的代码)。 What I'm trying to do now is to map those array values into groups collection and retrieve only those documents that are in the groupRef.
我现在要做的是将 map 这些数组值放入组集合中,并仅检索 groupRef 中的那些文档。 (Basically the goal is to just show in the UI the groups that the current user is a member of)
(基本上目标是在 UI 中显示当前用户所属的组)
user collection group collection用户集合组集合
const [groupsList, setGroupList] = useState([]);
const [groupRef, setGroupRef] = useState([]);
const [track, setTrack] = useState('')
const handleSubmit = () => {
setTrack('start')
fire.firestore().collection('users').doc(fire.auth().currentUser.uid).get().then((value) => {
console.log("userGroups " + value.data().userGroups) // this returns an object
setGroupRef([value.data().userGroups])
})
}
useEffect(() => {
handleSubmit()
}, [track])
console.log("sample list " + groupRef)
fire.firestore().collection('groups').onSnapshot(snapshot => (
setGroupList(snapshot.docs.map(doc => doc.data()))
))
^ this returns all the documents under groups collection. ^ 这将返回组集合下的所有文档。 any ideas how i can retrieve only those that the current user is a member of?
有什么想法我可以只检索当前用户所属的那些吗? any help would be much appreciated.
任何帮助将非常感激。 (ive been stuck on this for a long time. im also new to firebase.)
(我已经坚持了很长时间。我也是 firebase 的新手。)
@DougStevenson directed me to the right path of using array-contains which is a helper function on querying/getting data. @DougStevenson 指导我使用array-contains的正确路径,它是查询/获取数据的帮助程序 function。 the code below is the answer to my problem.
下面的代码是我的问题的答案。 this way is shorter and more efficient than the work i came up with.
这种方式比我想出的工作更短、更高效。
fire.firestore().collection('groups').where("groupMembers", "array-contains", fire.auth().currentUser.uid).onSnapshot(snapshot => ( setGroupList(snapshot.docs.map(doc => doc.data()))
))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.