![](/img/trans.png)
[英]Querying Firestore documents by Array or Map fields values in Firebase console
[英]Firebase Firestore - how to retrieve an array field from a specific document and use those array values to map documents
我有用戶和組 collections。在用戶集合下,每個文檔 ID 都是一個用戶 UID,每個用戶文檔都有一個數組字段“userGroups”,其中包含用戶所屬的組,這些組是組集合下組的文檔 ID。
我已經能夠檢索存儲在 groupRef 中的當前用戶的 userGroups 數組(請參見下面的代碼)。 我現在要做的是將 map 這些數組值放入組集合中,並僅檢索 groupRef 中的那些文檔。 (基本上目標是在 UI 中顯示當前用戶所屬的組)
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()))
))
^ 這將返回組集合下的所有文檔。 有什么想法我可以只檢索當前用戶所屬的那些嗎? 任何幫助將非常感激。 (我已經堅持了很長時間。我也是 firebase 的新手。)
@DougStevenson 指導我使用array-contains的正確路徑,它是查詢/獲取數據的幫助程序 function。 下面的代碼是我的問題的答案。 這種方式比我想出的工作更短、更高效。
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.